Exemplo n.º 1
0
        private void CorrectandSaveResultPosted(ResultPdfPostedXml resultPosted, CorporateAccount account)
        {
            if (resultPosted != null && !resultPosted.Customer.IsNullOrEmpty())
            {
                _logger.Info("Result posted Log for " + account.Tag);
                resultPosted = _resultPdfFileHelper.CorrectMissingRecords(resultPosted);

                if (account.Id == _settings.AppleCareAccountId || account.Id == _settings.MedMutualAccountId)
                {
                    var pdfLogfile = string.Format(_settings.PdfLogFilePath, account.FolderName);
                    if (account.Id == _settings.MedMutualAccountId)
                    {
                        pdfLogfile = pdfLogfile.Replace(" ", "");
                    }
                    pdfLogfile = Path.Combine(pdfLogfile, "Download");

                    try
                    {
                        _resultPdfFileHelper.CreateCsvForFileShared(resultPosted.Customer, pdfLogfile, account.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 " + account.Tag);
            }

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

            _resultPdfPostedSerializer.SerializeandSave(resultPostedToPlanFileName, resultPosted);
        }
Exemplo n.º 2
0
        public void Sync()
        {
            if (!_settings.SyncWithHra)
            {
                _logger.Info("Syncing with HRA is off ");
                return;
            }
            var reportGenerationConfigurationFilePath = _settings.MedicareSyncCustomSettingsPath + "EventTestSync.xml";
            var customSettings = _customSettingXmlSerializer.Deserialize(reportGenerationConfigurationFilePath);

            if (customSettings == null || !customSettings.LastTransactionDate.HasValue)
            {
                customSettings = new CustomSettings {
                    LastTransactionDate = DateTime.Today
                };
            }
            var fromTime = customSettings.LastTransactionDate ?? DateTime.Today;
            //get all tags for IsHealthPlan is true
            var orgName = _settings.OrganizationNameForHraQuestioner;
            var tags    = _corporateAccountRepository.GetHealthPlanTags();

            if (tags != null && tags.Any())
            {
                foreach (var tag in tags)
                {
                    _logger.Info("Medicare Event Test Sync for tag : " + tag);

                    // get todays Events For the Tag

                    var eventIds = _eventRepository.GetEventsByTag(fromTime, tag);
                    if (eventIds.Any())
                    {
                        _logger.Info("Medicare Event Count  : " + eventIds.Count + " " + String.Join(",", eventIds));
                        var pairs = _eventTestRepository.GetTestAliasesByEventIds(eventIds).ToList();
                        var model = new MedicareEventTestSyncModel {
                            Tag = tag, EventTestAliases = pairs, OrganizationName = orgName, TimeToken = DateTime.UtcNow.ToLongTimeString().Encrypt()
                        };
                        try
                        {
                            var result = _medicareApiService.PostAnonymous <bool>(_settings.MedicareApiUrl + MedicareApiUrl.SyncEventTest, model);
                            if (!result)
                            {
                                _logger.Info("Medicare Event Test Sync FAILED for tag : " + tag);
                            }
                        }
                        catch (Exception exception)
                        {
                            _logger.Error(" error occur Medicare Event Test Sync for tag: " + tag +
                                          " Message: " + exception.Message + "\n stack Trace: " +
                                          exception.StackTrace);
                        }
                    }
                }
            }
            customSettings.LastTransactionDate = DateTime.Today;
            _customSettingXmlSerializer.SerializeandSave(reportGenerationConfigurationFilePath, customSettings);
        }
        private void WriteXmlFile(IEnumerable <BcbsMiIncorrectPhoneViewModel> list, string tag, string fileName, DateTime toDate)
        {
            var dateAddedSetting = (from d in list
                                    select new DateAddedSettings
            {
                CustomerId = d.CustomerId,
                AddedDate = d.DateAddedtoReport
            }).ToList();

            DateAddedXml dateAddedXml = new DateAddedXml();

            dateAddedXml.AddedDate = dateAddedSetting;

            var dateAddedXmlFile = string.Format(_BcbsmiDateAddedIncorrectPhoneNumberSettingPath, tag, fileName + "_" + Convert.ToString(toDate.Year));

            _dateAddedSettingManager.SerializeandSave(dateAddedXmlFile, dateAddedXml);
        }
        private void SaveCustomersWithNoMrn(CorporateAccount account, List <long> customerIds)
        {
            var filePath = Path.Combine(_customerWithNoMrnPath, string.Format("CustomerWithNoMrn_{0}.xml", account.Tag));

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

            if (!customerIds.IsNullOrEmpty())
            {
                var customerWithNoMrnXml = new CustomerWithNoGmpiViewModel
                {
                    CustomerIds = customerIds
                };
                _customerWithNoMrn.SerializeandSave(filePath, customerWithNoMrnXml);
            }
        }
Exemplo n.º 5
0
        private void SaveResultNotPosted(string tag)
        {
            var filePath = GetResultNotPostedXmlFilePath(tag);

            DirectoryOperationsHelper.DeleteFileIfExist(filePath);

            if (_resultPdfNotPosted != null)
            {
                _resultPdfNotPostedSerializer.SerializeandSave(GetResultNotPostedXmlFilePath(tag), _resultPdfNotPosted);

                if (_resultPdfNotPosted.EventCustomer.Count > 0)
                {
                    _resultPdfEmailNotificationHelper.SendEmailNotificationForFileNotPosted(tag, _resultPdfNotPosted.EventCustomer.Count, _logger);
                }

                _resultPdfNotPosted = null;
            }
        }
Exemplo n.º 6
0
        public void PollForPdfDownload()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

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

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

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

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

                        DateTime?eventCutOfDate = _settings.PPEventCutOfDate;

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

                        var pcpResultReport = _mediaRepository.GetPdfFileNameForPcpResultReport();

                        var healthPlanResultReport = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();

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

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

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

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

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

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

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

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

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

                                        eventDirectoryPdf = healthPlanDownloadPath;

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

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

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

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

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

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

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

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

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

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

                                        var isFilePosted = true;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        if (resultNotPosted.EventCustomer.Count > 0)
                        {
                            _resultPdfEmailNotificationHelper.SendEmailNotificationForFileNotPosted(corporateAccount.Tag, resultNotPosted.EventCustomer.Count, _logger);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("some error occurred for AccountId: {0} and account tag: {1} Exception Message: \n{2}, \n stack Trace: \n\t {3} ", corporateAccount.Id, corporateAccount.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.Error(string.Format("some error occurred Exception Message: \n{0}, \n stack Trace: \n\t {1} ", exception.Message, exception.StackTrace));
            }
        }
        public void PollForPdfDownload()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

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

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

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

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

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

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

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

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

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

                        var pcpResultReport = _mediaRepository.GetPdfFileNameForPcpResultReport();

                        var healthPlanResultReport = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();

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

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

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

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

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

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

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

                            PostCustomerWithNoMrn(corporateAccount, destinationFolderPdf, resultPosted, customersWithNoMrn);

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

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

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

                            SaveCustomersWithNoMrn(corporateAccount, newCustomersWithNoMrn);
                        }

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

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

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

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

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

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

                        _resultPdfPostedSerializer.SerializeandSave(resultPostedToPlanFileName, resultPosted);

                        _logger.Info(string.Format("Result Pdf file Transfer completed for {0} ", corporateAccount.Tag));
                        _logger.Info("");
                        _logger.Info("");
                        _logger.Info("================================================================================");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("some error occured for AccountId: {0} and account tag: {1} Exception Message: \n{2}, \n stack Trace: \n\t {3} ", corporateAccount.Id, corporateAccount.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.Error(string.Format("some error occured Exception Message: \n{0}, \n stack Trace: \n\t {1} ", exception.Message, exception.StackTrace));
            }
        }
Exemplo n.º 8
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.º 9
0
        private void GenerateCrosswalkInboundReport(CrosswalkInboundFilter filter)
        {
            var account = _corporateAccountRepository.GetById(filter.AccountId);

            filter.Tag = account.Tag;

            if (account.IsHealthPlan)
            {
                filter.StopSendingPdftoHealthPlanDate = _settings.StopSendingPdftoHealthPlanDate;
            }

            var model = _crosswalkInboundReportService.GetCrosswalkInboundReportList(filter, _logger);

            if (model != null)
            {
                var folder = string.Format(_settings.FloridaBlueInboundReportPath, account.FolderName, DateTime.Now.ToString("yyyy-MM-dd"));
                if (!Directory.Exists(folder))
                {
                    DirectoryOperationsHelper.CreateDirectory(folder);
                }
                var fileName    = _pipeDelimitedReportHelper.GetReportName(ReportType.CrosswalkInbound) + ".txt";
                var zipFileName = _pipeDelimitedReportHelper.GetReportName(ReportType.CrosswalkZip);

                if (model.Collection != null && model.Collection.Any())
                {
                    _logger.Info("generating File");
                    var tempMediaLocation = _mediaRepository.GetTempMediaFileLocation().PhysicalPath + zipFileName + "\\";
                    if (!Directory.Exists(tempMediaLocation))
                    {
                        DirectoryOperationsHelper.CreateDirectory(tempMediaLocation);
                    }

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

                    foreach (var crosswalkViewModel in model.Collection)
                    {
                        var hafResultPdfLocation = _mediaRepository.GetPremiumVersionResultPdfLocation(crosswalkViewModel.EventId, crosswalkViewModel.CustomerId);
                        var hafResultPdfFileName = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();
                        var pcpResultPdfFileName = _mediaRepository.GetPdfFileNameForPcpResultReport();

                        _logger.Info(" Event Id: " + crosswalkViewModel.EventId + " Customer Id: " + crosswalkViewModel.CustomerId);

                        if (DirectoryOperationsHelper.IsFileExist(tempMediaLocation + crosswalkViewModel.FileName))
                        {
                            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(tempMediaLocation + crosswalkViewModel.FileName);
                            var files = DirectoryOperationsHelper.GetFiles(tempMediaLocation, fileNameWithoutExtension + "*.pdf");
                            crosswalkViewModel.FileName = fileNameWithoutExtension + "_" + files.Count() + ".pdf";
                        }

                        if (File.Exists(hafResultPdfLocation.PhysicalPath + hafResultPdfFileName))
                        {
                            var destinationFileName = GetFileName(resultPosted.Customer, crosswalkViewModel.EventId, crosswalkViewModel.CustomerId, Path.GetFileNameWithoutExtension(crosswalkViewModel.FileName), (long)ResultFormatType.PDF);
                            crosswalkViewModel.FileName = destinationFileName + ".pdf";

                            _logger.Info("Copying File.. filePath from : " + hafResultPdfLocation.PhysicalPath + hafResultPdfFileName);
                            _logger.Info("Copying File.. filePath To : " + tempMediaLocation + crosswalkViewModel.FileName);

                            DirectoryOperationsHelper.Copy(hafResultPdfLocation.PhysicalPath + hafResultPdfFileName, tempMediaLocation + crosswalkViewModel.FileName);

                            resultPosted.Customer.Add(GetCustomerInfo(crosswalkViewModel));
                        }
                        else if (File.Exists(hafResultPdfLocation.PhysicalPath + pcpResultPdfFileName))
                        {
                            var destinationFileName = GetFileName(resultPosted.Customer, crosswalkViewModel.EventId, crosswalkViewModel.CustomerId, Path.GetFileNameWithoutExtension(crosswalkViewModel.FileName), (long)ResultFormatType.PDF);
                            crosswalkViewModel.FileName = destinationFileName + ".pdf";

                            _logger.Info("Copying File.. filePath from : " + hafResultPdfLocation.PhysicalPath + pcpResultPdfFileName);
                            _logger.Info("Copying File.. filePath To : " + tempMediaLocation + crosswalkViewModel.FileName);

                            DirectoryOperationsHelper.Copy(hafResultPdfLocation.PhysicalPath + pcpResultPdfFileName, tempMediaLocation + crosswalkViewModel.FileName);

                            resultPosted.Customer.Add(GetCustomerInfo(crosswalkViewModel));
                        }
                        else
                        {
                            _logger.Info("file not found");
                        }
                    }

                    _resultPdfPostedSerializer.SerializeandSave(resultPostedToPlanFileName, resultPosted);

                    _pipeDelimitedReportHelper.Write(model.Collection, folder, fileName);
                    DirectoryOperationsHelper.Copy(folder + "\\" + fileName, tempMediaLocation + fileName);

                    _logger.Info("generating Zip ");
                    _zipHelper.CreateZipFiles(tempMediaLocation, folder + "\\" + zipFileName + ".zip");

                    if (_sendReportToSftp)
                    {
                        try
                        {
                            _logger.Info("Sending zip to SFTP.");

                            var destinationPath = _destinationSftpPath + "\\" + account.FolderName + "\\Download\\Reports";
                            SendFilesToSftp(Path.Combine(folder, zipFileName + ".zip"), destinationPath, zipFileName + ".zip");

                            _logger.Info("Zip sent to SFTP.");
                        }
                        catch (Exception ex)
                        {
                            _logger.Info("Error sending zip to SFTP.");
                            _logger.Error("Message : " + ex.Message);
                            _logger.Error("Stack Trace : " + ex.StackTrace);
                        }
                    }

                    _logger.Info("Deleting temp folder: " + tempMediaLocation);
                    DirectoryOperationsHelper.DeleteDirectory(tempMediaLocation, true);

                    _logger.Info("Deleting text file: " + folder + "\\" + fileName);
                    DirectoryOperationsHelper.Delete(folder + "\\" + fileName);
                }
                else
                {
                    _logger.Info("No Data found for account Id: " + filter.AccountId);
                }
            }
            else
            {
                _logger.Info("No record found for " + account.Tag);
            }
        }
Exemplo n.º 10
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));
            }
        }
Exemplo n.º 11
0
        private void SetResultPostedList(string tag, ResultPdfPostedXml resultPdfPosted)
        {
            var resultPostedToPlanFileName = Path.Combine(_resultPostedToPlanPath, string.Format("ResultPostedto_{0}.xml", tag));

            _resultPdfPostedSerializer.SerializeandSave(resultPostedToPlanFileName, resultPdfPosted);
        }
Exemplo n.º 12
0
        public IEnumerable <EventCustomerScreeningAggregate> Parse()
        {
            var eventCustomerAggregates = new List <EventCustomerScreeningAggregate>();
            var mediaLocation           = _mediaRepository.GetEawvHraResultMediaLocation();
            var mediaArchiveLocation    = _mediaRepository.GetEawvHraResultArchiveMediaLocation();

            try
            {
                var xmlFilePaths = Directory.GetFiles(mediaLocation.PhysicalPath, "*.xml");

                foreach (var xmlfile in xmlFilePaths)
                {
                    _logger.Info("reading xml File: " + xmlfile);
                    HraResultTags eawvHraResult = null;
                    try
                    {
                        eawvHraResult = _eawvHraSerializer.Deserialize(xmlfile);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Some error occurred while reading xml. Message: " + ex.Message);
                        _logger.Error("Stack Trace: " + ex.StackTrace);
                        File.Move(xmlfile, Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile)));
                    }

                    if (eawvHraResult == null)
                    {
                        _logger.Info("Some error occurred while reading xml.");
                        File.Move(xmlfile, Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile)));
                    }

                    if (eawvHraResult.Events.IsNullOrEmpty())
                    {
                        _logger.Info("No Event Data found for Tag: " + eawvHraResult.Name);
                        File.Move(xmlfile, Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile)));
                        continue;
                    }

                    var eventid = eawvHraResult.Events.First().EventId;

                    var account = _corporateAccountRepository.GetbyEventId(eventid);

                    if (account == null)
                    {
                        _logger.Info("No Corporate Account For Event Id: " + eventid);
                        File.Move(xmlfile, Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile)));
                        continue;
                    }

                    _logger.Info("Running for corporate Account " + account.Tag);

                    var theEvent = _eventRepository.GetById(eventid);

                    QuestionnaireType questionnaireType = QuestionnaireType.None;
                    if (account != null && account.IsHealthPlan && theEvent != null)
                    {
                        questionnaireType = _accountHraChatQuestionnaireHistoryServices.QuestionnaireTypeByAccountIdandEventDate(account.Id, theEvent.EventDate);
                    }

                    if (questionnaireType != QuestionnaireType.HraQuestionnaire)
                    {
                        _logger.Info("HRA Questionnaire is not started");
                        continue;
                    }

                    var eawvTestNotPurchsed = new HraResultTags
                    {
                        Name   = eawvHraResult.Name,
                        Events = new List <HraResultEvent>()
                    };

                    foreach (var hraResultEvent in eawvHraResult.Events)
                    {
                        var eventCustomers = _eventCustomerRepository.GetbyEventId(hraResultEvent.EventId);

                        if (eventCustomers.IsNullOrEmpty())
                        {
                            _logger.Info("No Event Cusotmer found");
                            continue;
                        }

                        var customeridNotToParse = eventCustomers.Where(x => x.NoShow || x.LeftWithoutScreeningReasonId.HasValue).Select(x => x.CustomerId);

                        var snapshotFolderPath     = Path.Combine(mediaLocation.PhysicalPath, eawvHraResult.Name, hraResultEvent.EventId.ToString(), HraFolderSnapshot);
                        var preventionFolderPlan   = Path.Combine(mediaLocation.PhysicalPath, eawvHraResult.Name, hraResultEvent.EventId.ToString(), HraFolderPreventionPlan);
                        var resultReportFolderPath = Path.Combine(mediaLocation.PhysicalPath, eawvHraResult.Name, hraResultEvent.EventId.ToString(), HraFolderResultReport);

                        var snapShotCustomerIds       = (hraResultEvent.Snapshot != null && !hraResultEvent.Snapshot.CustomerId.IsNullOrEmpty()) ? hraResultEvent.Snapshot.CustomerId.Where(c => !customeridNotToParse.Contains(c)).Select(c => c).Distinct() : new List <long>();
                        var preventionPlanCustomerIds = (hraResultEvent.PreventionPlan != null && !hraResultEvent.PreventionPlan.CustomerId.IsNullOrEmpty()) ? hraResultEvent.PreventionPlan.CustomerId.Where(c => !customeridNotToParse.Contains(c)).Select(c => c).Distinct() : new List <long>();
                        var resultReportCustomerIds   = (hraResultEvent.ResultReport != null && !hraResultEvent.ResultReport.CustomerId.IsNullOrEmpty()) ? hraResultEvent.ResultReport.CustomerId.Where(c => !customeridNotToParse.Contains(c)).Select(c => c).Distinct() : new List <long>();

                        _logger.Info(string.Format("============================Reading Snapshot for Tag:{0} EventId {1}=================================", eawvHraResult.Name, hraResultEvent.EventId));
                        _logger.Info(string.Format("snapshot folder Path: {0}", snapshotFolderPath));

                        var customerTestNotPurchased = new List <long>();
                        if (Directory.Exists(snapshotFolderPath))
                        {
                            _logger.Info("Count: " + snapShotCustomerIds.Count());
                            foreach (var customerId in snapShotCustomerIds)
                            {
                                var snapShotFilePath = Path.Combine(snapshotFolderPath, customerId + ".pdf");

                                if (!File.Exists(snapShotFilePath))
                                {
                                    _logger.Info("SnapShot File does not exist at following location: " + snapShotFilePath);
                                    continue;
                                }

                                _logger.Info("SnapShot File exists at location: " + snapShotFilePath);

                                var isEAwvTestPurchasedByCustomer = _testResultService.IsTestPurchasedByCustomer(hraResultEvent.EventId, customerId, (long)TestType.eAWV);

                                if (!isEAwvTestPurchasedByCustomer)
                                {
                                    customerTestNotPurchased.Add(customerId);
                                    _logger.Info("EAWV : EAWV tests is not availed by CustomerId [" + customerId + "].\n");
                                    continue;
                                }

                                try
                                {
                                    var mediaFiles = new List <ResultMedia>();

                                    string folderToSavePdf = _mediaRepository.GetResultMediaFileLocation(customerId, hraResultEvent.EventId).PhysicalPath;
                                    _logger.Info("Get Snapshot Media");
                                    var snapShotResultMedia = GetMediaFromPdfFile(snapShotFilePath, folderToSavePdf, TestType.eAWV, AwvFileTypes.SnapShot);

                                    if (snapShotResultMedia != null)
                                    {
                                        _logger.Info("Inside SpanShot Result Media");

                                        snapShotResultMedia.ReadingSource = ReadingSource.Automatic;

                                        mediaFiles.Add(snapShotResultMedia);

                                        if (preventionPlanCustomerIds.Any(c => c == customerId))
                                        {
                                            var preventionPlanFile = Path.Combine(preventionFolderPlan,
                                                                                  customerId + ".pdf");

                                            if (File.Exists(preventionPlanFile))
                                            {
                                                var preventionPlanMedia = GetMediaFromPdfFile(preventionPlanFile,
                                                                                              folderToSavePdf, TestType.eAWV, AwvFileTypes.PreventionPlan);
                                                if (preventionFolderPlan != null)
                                                {
                                                    preventionPlanMedia.ReadingSource = ReadingSource.Automatic;
                                                    mediaFiles.Add(preventionPlanMedia);
                                                    preventionPlanCustomerIds =
                                                        preventionPlanCustomerIds.Where(c => c != customerId).ToList();
                                                }
                                            }
                                            else
                                            {
                                                _logger.Info(
                                                    "Prevention Plan File does not exist at following location: " +
                                                    preventionPlanFile);
                                            }
                                        }

                                        if (resultReportCustomerIds.Any(c => c == customerId))
                                        {
                                            var resultReportFile = Path.Combine(resultReportFolderPath,
                                                                                customerId + ".pdf");

                                            if (File.Exists(resultReportFile))
                                            {
                                                var resultExportMedia = GetMediaFromPdfFile(resultReportFile,
                                                                                            folderToSavePdf, TestType.eAWV, AwvFileTypes.ResultExport);
                                                if (resultExportMedia != null)
                                                {
                                                    resultExportMedia.ReadingSource = ReadingSource.Automatic;
                                                    mediaFiles.Add(resultExportMedia);

                                                    resultReportCustomerIds =
                                                        resultReportCustomerIds.Where(c => c != customerId).ToList();
                                                }
                                            }
                                            else
                                            {
                                                _logger.Info(
                                                    "Result Report File does not exist at following location: " +
                                                    resultReportFile);
                                            }
                                        }
                                        var testResult = new EAwvTestResult {
                                            ResultImages = mediaFiles
                                        };

                                        _logger.Info("Inside SnapShot for adding Customer Aggregate");
                                        _resultParserHelper.AddTestResulttoEventCustomerAggregate(
                                            eventCustomerAggregates, hraResultEvent.EventId, customerId, testResult);
                                        _resultParserHelper.AddResultArchiveLog(string.Empty, TestType.eAWV, customerId,
                                                                                MedicalEquipmentTag.HRA);
                                    }
                                    else
                                    {
                                        _logger.Info("SpanShot Result Media Not Found");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.Error("EAwv HRA: System Failure! Message: " + ex.Message + "\n\t Stack Trace: " + ex.StackTrace);
                                    _resultParserHelper.AddResultArchiveLog(ex.Message, TestType.eAWV, customerId, MedicalEquipmentTag.HRA);
                                }
                            }
                        }
                        else
                        {
                            _logger.Info("Snapshot Directory does not exit for EventId " + hraResultEvent.EventId);
                            _logger.Info("Snapshot Directory Path " + hraResultEvent.EventId);
                        }

                        _logger.Info(string.Format("============================Reading Prevention Plan for Tag:{0} EventId {1}=================================", eawvHraResult.Name, hraResultEvent.EventId));
                        _logger.Info(string.Format("Prevention Plan folder Path: {0}", preventionFolderPlan));


                        if (Directory.Exists(preventionFolderPlan))
                        {
                            foreach (var customerId in preventionPlanCustomerIds)
                            {
                                var preventionFilePath = Path.Combine(preventionFolderPlan, customerId + ".pdf");

                                if (!File.Exists(preventionFilePath))
                                {
                                    _logger.Info("Prevention Plan File does not exist at following location: " + preventionFilePath);
                                    continue;
                                }

                                var isEAwvTestPurchasedByCustomer = _testResultService.IsTestPurchasedByCustomer(hraResultEvent.EventId, customerId, (long)TestType.eAWV);

                                if (!isEAwvTestPurchasedByCustomer)
                                {
                                    customerTestNotPurchased.Add(customerId);
                                    _logger.Info("EAWV : EAWV tests is not availed by CustomerId [" + customerId + "].\n");
                                    continue;
                                }
                                try
                                {
                                    var    mediaFiles                = new List <ResultMedia>();
                                    string folderToSavePdf           = _mediaRepository.GetResultMediaFileLocation(customerId, hraResultEvent.EventId).PhysicalPath;
                                    var    preventionPlanResultMedia = GetMediaFromPdfFile(preventionFilePath, folderToSavePdf, TestType.eAWV, AwvFileTypes.PreventionPlan);

                                    if (preventionPlanResultMedia != null)
                                    {
                                        preventionPlanResultMedia.ReadingSource = ReadingSource.Automatic;
                                        mediaFiles.Add(preventionPlanResultMedia);

                                        if (resultReportCustomerIds.Any(c => c == customerId))
                                        {
                                            var resultReportFile = Path.Combine(resultReportFolderPath, customerId + ".pdf");

                                            if (File.Exists(resultReportFile))
                                            {
                                                var resultExportaMedia = GetMediaFromPdfFile(resultReportFile, folderToSavePdf, TestType.eAWV, AwvFileTypes.ResultExport);
                                                if (resultExportaMedia != null)
                                                {
                                                    resultExportaMedia.ReadingSource = ReadingSource.Automatic;
                                                    mediaFiles.Add(resultExportaMedia);

                                                    resultReportCustomerIds = resultReportCustomerIds.Where(c => c != customerId).ToList();
                                                }
                                            }
                                            else
                                            {
                                                _logger.Info("Result Report File does not exist at following location: " + resultReportFile);
                                            }
                                        }
                                        var testResult = new EAwvTestResult {
                                            ResultImages = mediaFiles
                                        };
                                        _logger.Info("Inside PreventionPLan for adding Customer Aggregate");
                                        _resultParserHelper.AddTestResulttoEventCustomerAggregate(eventCustomerAggregates, hraResultEvent.EventId, customerId, testResult);
                                        _resultParserHelper.AddResultArchiveLog(string.Empty, TestType.eAWV, customerId, MedicalEquipmentTag.HRA);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.Error("EAwv HRA: System Failure! Message: " + ex.Message + "\n\t Stack Trace: " + ex.StackTrace);
                                    _resultParserHelper.AddResultArchiveLog(ex.Message, TestType.eAWV, customerId, MedicalEquipmentTag.HRA);
                                }
                            }
                        }
                        else
                        {
                            _logger.Info("Prevention Plan Directory does not exit for EventId " + hraResultEvent.EventId);
                            _logger.Info("Prevention Plan Directory Path " + hraResultEvent.EventId);
                        }

                        _logger.Info(string.Format("============================Reading Result Report for Tag:{0} EventId {1}=================================", eawvHraResult.Name, hraResultEvent.EventId));
                        _logger.Info(string.Format("Result Report folder Path: {0}", resultReportFolderPath));


                        if (Directory.Exists(resultReportFolderPath))
                        {
                            foreach (var customerId in resultReportCustomerIds)
                            {
                                var resultReportFilePath = Path.Combine(resultReportFolderPath, customerId + ".pdf");

                                if (!File.Exists(resultReportFilePath))
                                {
                                    _logger.Info("Result Report File does not exist at following location: " + resultReportFilePath);
                                    continue;
                                }

                                var isEAwvTestPurchasedByCustomer = _testResultService.IsTestPurchasedByCustomer(hraResultEvent.EventId, customerId, (long)TestType.eAWV);

                                if (!isEAwvTestPurchasedByCustomer)
                                {
                                    customerTestNotPurchased.Add(customerId);
                                    _logger.Info("EAWV : EAWV tests is not availed by CustomerId [" + customerId + "].\n");
                                    continue;
                                }
                                try
                                {
                                    var    mediaFiles        = new List <ResultMedia>();
                                    string folderToSavePdf   = _mediaRepository.GetResultMediaFileLocation(customerId, hraResultEvent.EventId).PhysicalPath;
                                    var    resultExportMedia = GetMediaFromPdfFile(resultReportFilePath, folderToSavePdf, TestType.eAWV, AwvFileTypes.ResultExport);

                                    if (resultExportMedia != null)
                                    {
                                        resultExportMedia.ReadingSource = ReadingSource.Automatic;
                                        mediaFiles.Add(resultExportMedia);

                                        var testResult = new EAwvTestResult {
                                            ResultImages = mediaFiles
                                        };
                                        _logger.Info("Inside Result Report for adding Customer Aggregate");
                                        _resultParserHelper.AddTestResulttoEventCustomerAggregate(eventCustomerAggregates, hraResultEvent.EventId, customerId, testResult);
                                        _resultParserHelper.AddResultArchiveLog(string.Empty, TestType.eAWV, customerId, MedicalEquipmentTag.HRA);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.Error("EAwv HRA: System Failure! Message: " + ex.Message + "\n\t Stack Trace: " + ex.StackTrace);
                                    _resultParserHelper.AddResultArchiveLog(ex.Message, TestType.eAWV, customerId, MedicalEquipmentTag.HRA);
                                }
                            }
                        }
                        else
                        {
                            _logger.Info("Result Report Directory does not exit for EventId " + hraResultEvent.EventId);
                            _logger.Info("Result Report Directory Path " + hraResultEvent.EventId);
                        }

                        if (!customerTestNotPurchased.IsNullOrEmpty())
                        {
                            eawvTestNotPurchsed.Events.Add(new HraResultEvent
                            {
                                EventId        = hraResultEvent.EventId,
                                PreventionPlan = new HraResultPreventionPlan {
                                    CustomerId = customerTestNotPurchased.ToList()
                                },
                                Snapshot = new HraResultSnapshot {
                                    CustomerId = customerTestNotPurchased.ToList()
                                },
                                ResultReport = new HraResultReport()
                                {
                                    CustomerId = customerTestNotPurchased.ToList()
                                }
                            });
                        }
                    }
                    if (!eawvTestNotPurchsed.Events.IsNullOrEmpty())
                    {
                        _eawvHraSerializer.SerializeandSave(Path.Combine(mediaLocation.PhysicalPath, "customerNotPurchaseTest_" + DateTime.Now.ToFileTime() + ".xml"), eawvTestNotPurchsed);
                    }

                    try
                    {
                        var archiveFileName = Path.Combine(mediaArchiveLocation.PhysicalPath, Path.GetFileName(xmlfile));
                        if (File.Exists(archiveFileName))
                        {
                            File.Delete(archiveFileName);
                        }
                        File.Move(xmlfile, archiveFileName);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Error while moving XML File in Archive folder");
                        _logger.Info(string.Format("Message: {0}", ex.Message));
                        _logger.Info(string.Format("stackTrace: {0}", ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Some Error occurred while parsing Eawv Result");
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.StackTrace);
            }

            _logger.Info("EAWVParser eventCustomerAggregates count " + eventCustomerAggregates.Count);
            return(eventCustomerAggregates);
        }
Exemplo n.º 13
0
        public void GenerateJsonforEventCustomers(Event eventData, ILogger logger)
        {
            int totalrecords;

            logger.Info("Getting event customers......");

            var eventCusomters = _eventCustomerRepository.GetMyBioCheckEventCustomers(1, 400, new MyBioCheckCustomerModelFilter {
                EventId = eventData.Id
            }, out totalrecords);

            if (eventCusomters == null || !eventCusomters.Any())
            {
                logger.Info(string.Format("No event customers found for Event Id {0} EventDate {1}", eventData.Id, eventData.EventDate));
                return;
            }

            logger.Info(string.Format("{0} event customers found.", eventCusomters.Count()));

            var eventCustomerIds = eventCusomters.Select(x => x.Id).ToArray();
            var customerIds      = eventCusomters.Select(x => x.CustomerId).ToArray();

            var          customers = _customerRepository.GetCustomers(customerIds);
            var          healthAssessmentAnswer = _healthAssessmentRepository.GetCustomerHealthInfoByEventCustomerIds(eventCustomerIds);
            var          account      = _corporateAccountRepository.GetbyEventId(eventData.Id);
            Organization organization = null;

            if (account != null)
            {
                organization = _organizationRepository.GetOrganizationbyId(account.Id);
                account.Name = organization.Name;
            }


            DirectoryOperationsHelper.CreateDirectoryIfNotExist(_bioCheckAssessmentFailedListPath);

            var fileName = Path.Combine(_bioCheckAssessmentFailedListPath, string.Format("failedCustomerRecord_{0}.xml", DateTime.Now.Ticks));

            var failedCustomerList = new BioCheckAssessmentFailedList {
                EventCustomers = new List <BioCheckAssessmentFailed>()
            };

            var eventCustomerResultTrales = _eventCustomerResultTraleRepository.GetByEventCustomerResultIds(eventCustomerIds);
            var customerTrales            = _customerTraleRepository.GetByCustomerIds(customerIds);

            eventCustomerResultTrales = eventCustomerResultTrales.IsNullOrEmpty() ? new List <EventCustomerResultTrale>() : eventCustomerResultTrales.ToList();
            customerTrales            = customerTrales.IsNullOrEmpty() ? new List <CustomerTrale>() : customerTrales;

            foreach (var ec in eventCusomters)
            {
                try
                {
                    var customer  = customers.Single(c => c.CustomerId == ec.CustomerId);
                    var hafAnswer = healthAssessmentAnswer.Where(c => c.EventCustomerId == ec.Id);

                    logger.Info("Started For EventId: " + ec.EventId + " customerId: " + ec.CustomerId);

                    var bioCheckJsonViewModel = GenerateBioCheckResponseModel(ec, customer, hafAnswer, eventData, logger, eventCustomerResultTrales, customerTrales, account);

                    if (bioCheckJsonViewModel != null)
                    {
                        bioCheckJsonViewModel.ProfileId = _profileId;
                        logger.Info("Saving Request JSON For eventId: " + ec.EventId + " customerId: " + ec.CustomerId);
                        SaveRequestJson(bioCheckJsonViewModel, ec.EventId, ec.CustomerId);

                        logger.Info("Submitting Post Request For eventId: " + ec.EventId + " customerId: " + ec.CustomerId);
                        var response        = _trailApiService.Post <BioCheckJsonViewModel>(bioCheckJsonViewModel);
                        var isNewResultFlow = eventData.EventDate >= _settings.ResultFlowChangeDate;

                        if (response != null)
                        {
                            logger.Info("Saving response For EventId: " + ec.EventId + " customerId: " + ec.CustomerId);
                            SaveReports(response, ec.EventId, ec.CustomerId, logger, isNewResultFlow);
                        }
                        else
                        {
                            logger.Info("No Response found for EventId: " + ec.EventId + " customerId: " + ec.CustomerId);
                        }
                    }
                    logger.Info("Complete For EventId: " + ec.EventId + " customerId: " + ec.CustomerId);
                }
                catch (Exception exception)
                {
                    failedCustomerList.EventCustomers.Add(new BioCheckAssessmentFailed {
                        CustomerId = ec.CustomerId, EventId = ec.EventId
                    });
                    logger.Error(string.Format("Error while generating My Bio-Check Assessment Data for customer Id: {0} and EventId {1} Message: {2}, StackTrace {3}", ec.CustomerId, ec.EventId, exception.Message, exception.StackTrace));
                }
            }

            if (!failedCustomerList.EventCustomers.IsNullOrEmpty())
            {
                _bioCheckAssessmentFailedListXmlSerializer.SerializeandSave(fileName, failedCustomerList);
            }
        }
        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 PollForClinicalDocument()
        {
            if (_accountIds.IsNullOrEmpty())
            {
                return;
            }
            var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

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

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

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

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

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

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

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

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

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

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

                            DirectoryOperationsHelper.DeleteFileIfExist(filePath);

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

                    _logger.Info("compeletd  For Account Id..... " + account.Id);
                }
                catch (Exception exception)
                {
                    _logger.Error("some Exception occured while generating CCD Xml for account Tag " + account.Tag);
                    _logger.Error("Message: " + exception.Message);
                    _logger.Error("Stack Trace: " + exception.StackTrace);
                }
            }
        }
Exemplo n.º 16
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));
            }
        }
        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));
            }
        }
        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));
            }
        }