public void PollForParsePatientDataFromAces()
        {
            try
            {
                _logger.Info("Entering Parse Patient Data From Aces Polling Agent @:" + DateTime.Now);

                var sftpFileLocation = _settings.ParsePatientDataSftpPath;
                var mediaLocation    = _mediaRepository.GetParsePatientDataMediaFileLocation();

                var archiveFolder = Path.Combine(mediaLocation.PhysicalPath, "Archive", DateTime.Today.ToString("yyyyMMdd"));
                var failedFolder  = Path.Combine(mediaLocation.PhysicalPath, "Failed", DateTime.Today.ToString("yyyyMMdd"));

                var getFilesFromSftp = DirectoryOperationsHelper.GetFiles(sftpFileLocation, "TCPA_AcesID_HipID*.txt");

                if (getFilesFromSftp.IsNullOrEmpty())
                {
                    _logger.Info("No files found for parsing.");
                    return;
                }

                DirectoryOperationsHelper.CreateDirectoryIfNotExist(archiveFolder);

                foreach (var file in getFilesFromSftp)
                {
                    var fileName = Path.GetFileName(file);
                    MoveFile(file, Path.Combine(mediaLocation.PhysicalPath, fileName));
                }

                var filesToParse = DirectoryOperationsHelper.GetFiles(mediaLocation.PhysicalPath, "*.txt");
                _logger.Info("Number of files to Parse:" + filesToParse.Count());
                const int pageSize = 100;

                foreach (var file in filesToParse)
                {
                    try
                    {
                        var fileName   = Path.GetFileName(file);
                        var sourceFile = Path.Combine(mediaLocation.PhysicalPath, fileName);

                        var patientData   = _pipeDelimitedReportHelper.Read(sourceFile);
                        var recordsInFile = patientData.Rows.Count;
                        if (recordsInFile == 0)
                        {
                            _logger.Info("No record found in " + fileName);
                            MoveFile(sourceFile, Path.Combine(archiveFolder, fileName));
                            continue;
                        }
                        _logger.Info("Parsing file: " + fileName);
                        _logger.Info("Total number of records to file: " + recordsInFile);
                        var failedRecords     = new List <PatientParsedDataViewModel>();
                        var parsedPatientData = ParsePatientData(patientData.AsEnumerable(), failedRecords);
                        if (parsedPatientData.Any())
                        {
                            var pageNumber   = 1;
                            int totalRecords = parsedPatientData.Count();

                            var totalPages = (totalRecords / pageSize) + (totalRecords % pageSize != 0 ? 1 : 0);
                            do
                            {
                                var pagedCustomers    = parsedPatientData.Skip(pageSize * (pageNumber - 1)).Take(pageSize);
                                var parsedCustomerIds = pagedCustomers.Select(x => x.CustomerId).ToArray();
                                var customerIds       = _customerRepository.CheckCustomerExists(parsedCustomerIds).ToArray();
                                if (parsedCustomerIds.Count() != customerIds.Count())
                                {
                                    var customerIdNotExist = parsedCustomerIds.Except(customerIds);
                                    var failedCustomers    = pagedCustomers.Where(x => customerIdNotExist.Contains(x.CustomerId));
                                    failedCustomers.ForEach(x => x.Error = "HIPID does not exist.");
                                    failedRecords.AddRange(failedCustomers);
                                    pagedCustomers = pagedCustomers.Where(x => customerIds.Contains(x.CustomerId));
                                }

                                var customerIdsAlreadyHaveAcesId = _customerRepository.CheckCustomerAlreadyHaveAcesId(customerIds);
                                if (customerIdsAlreadyHaveAcesId.Count() != 0)
                                {
                                    var customersAlreadyHaveAcesId = pagedCustomers.Where(x => customerIdsAlreadyHaveAcesId.Contains(x.CustomerId));
                                    customersAlreadyHaveAcesId.ForEach(x => x.Error = "Patient already have ACESID.");
                                    failedRecords.AddRange(customersAlreadyHaveAcesId);
                                    pagedCustomers = pagedCustomers.Where(x => !customerIdsAlreadyHaveAcesId.Contains(x.CustomerId));
                                }

                                var acesIdAlreadyAssignedToCustomers = _customerRepository.CheckAcesIdAlreadyAssignedToCustomer(pagedCustomers.Select(x => x.AcesId.ToLower()).ToArray());
                                if (acesIdAlreadyAssignedToCustomers.Count() != 0)
                                {
                                    var acesIdAlreadyAssignedCustomers = pagedCustomers.Where(x => acesIdAlreadyAssignedToCustomers.Contains(x.AcesId));
                                    acesIdAlreadyAssignedCustomers.ForEach(x => x.Error = "ACESID already assigned to a patient.");
                                    failedRecords.AddRange(acesIdAlreadyAssignedCustomers);
                                    pagedCustomers = pagedCustomers.Where(x => !acesIdAlreadyAssignedToCustomers.Contains(x.AcesId.ToLower()));
                                }
                                _logger.Info(string.Format("Number of customer to parse: {0} in page: {1}", pagedCustomers.Count(), pageNumber));
                                foreach (var customer in pagedCustomers)
                                {
                                    try
                                    {
                                        _logger.Info("Parsing data for CustomerId: " + customer.CustomerId);
                                        var customerEligibility      = _customerEligibilityRepository.GetByCustomerIdAndYear(customer.CustomerId, DateTime.Today.Year);
                                        var customerProfileHistoryId = _customerProfileHistoryRepository.CreateCustomerHistory(customer.CustomerId, orgRoleId, customerEligibility);
                                        _eventCustomerRepository.UpdateCustomerProfileIdByCustomerId(customer.CustomerId, customerProfileHistoryId);
                                        _customerRepository.UpdateAcesId(customer.CustomerId, customer.AcesId);
                                    }
                                    catch (Exception ex)
                                    {
                                        failedRecords.Add(new PatientParsedDataViewModel()
                                        {
                                            AcesId = customer.AcesId, CustomerId = customer.CustomerId, Error = "Some error occurred while updating."
                                        });
                                        _logger.Error(string.Format("Error occurred while updating record for CustomerId: {0}.\nMessage: {1}\n\tStackTrace: {2}", customer.CustomerId, ex.Message, ex.StackTrace));
                                    }
                                }

                                pageNumber++;
                            }while (totalPages >= pageNumber);
                        }
                        CreateFailedPatientFile(fileName, failedFolder, failedRecords);
                        MoveFile(sourceFile, Path.Combine(archiveFolder, fileName));
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Error occurred while processing the {0}.\nMessage: {1}\n\tStackTrace: {2}", file, ex.Message, ex.StackTrace));
                        var fileName = Path.GetFileName(file);
                        MoveFile(file, Path.Combine(archiveFolder, fileName));
                    }
                }
                _logger.Info("File parsing completed @ " + DateTime.Now);
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Exception occurred during execution of servcie. \nException Message: {0}\n\tStackTrace:{1}", ex.Message, ex.StackTrace));
                return;
            }
        }
        public void CreateZipFile()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);
                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Creating zip for accountId {0} and account tag {1}. ", account.Id, account.Tag));

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

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

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

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

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

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

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

                        var directoryToDeleteFrom = new DirectoryInfo(destinationPath);

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

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

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

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

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

                        _zipHelper.CreateZipFiles(sourceFile, destinationfile, true);


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

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

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

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

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

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

                        _logger.Info("Zip File Created");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Some Error occurred for Account Id " + account.Id + " Account Tag " + account.Tag);
                        _logger.Error("Message " + ex.Message);
                        _logger.Error("Stack Trace " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Some Error occurred ");
                _logger.Error("Message " + ex.Message);
                _logger.Error("Stack Trace " + ex.StackTrace);
            }
        }
        public void ResultExport()
        {
            try
            {
                string[] showAdditionalFields = null;
                if (!string.IsNullOrEmpty(_settings.AnthemAdditionalFieldValues))
                {
                    showAdditionalFields = _settings.AnthemAdditionalFieldValues.Split(new char[','], StringSplitOptions.RemoveEmptyEntries);
                }

                foreach (var customTag in _customTags)
                {
                    try
                    {
                        _logger.Info("Running report for CustomTag: " + customTag);
                        var corporateTag = _corporateTagRepository.GetByTag(customTag);

                        if (corporateTag == null)
                        {
                            _logger.Info("No Corporate Tag Found: " + customTag);
                            continue;
                        }
                        var account = (_corporateAccountRepository).GetById(corporateTag.CorporateId);

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

                        var folderStateCode = string.Empty;
                        if (account.Id == _anthemAccountId)
                        {
                            folderStateCode = "CA";
                        }
                        else
                        {
                            foreach (var stateCode in _settings.AnthemCustomTagStates)
                            {
                                if (customTag.Contains(stateCode))
                                {
                                    folderStateCode = stateCode.Substring(stateCode.Length - 2);

                                    break;
                                }
                            }
                        }

                        if (folderStateCode == string.Empty)
                        {
                            continue;
                        }

                        var destinationPath = string.Format(_settings.AnthemDownloadPath, folderStateCode);
                        destinationPath = Path.Combine(destinationPath, "results");

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

                        var customSettings = _customSettingManager.Deserialize(resultExportSettings);

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

                        var toDate = DateTime.Now;

                        CreateDistinationDirectory(destinationPath);

                        CreateDistinationDirectory(_accumulativeResultExportsPath);
                        CreateDistinationDirectory(_incrementalResultExportsPath);

                        var customTags = new[] { customTag };

                        var finalFilename   = string.Format("HLTHFAIR_ResultsExport_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));
                        var incrementalFile = string.Format(@"ResultExport_{0}_{1}.csv", account.Tag, Guid.NewGuid());

                        var cumulativeFilePath  = Path.Combine(_accumulativeResultExportsPath, string.Format(@"ResultExport_{0}_{1}.csv", account.Tag, DateTime.Today.Year));
                        var incrementalFilePath = Path.Combine(_incrementalResultExportsPath, incrementalFile);

                        var finalFilePath = Path.Combine(destinationPath, finalFilename);

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

                        _pcpResultExportServiceHelper.ResultExport(fromDate, toDate, account.Id, _incrementalResultExportsPath, account.Tag, customTags, resultExportFileName: incrementalFile, considerEventDate: true, eventStartDate: fromDate.GetFirstDateOfYear(), eventEndDate: fromDate.GetLastDateOfYear(), showHiddenAdditionalFields: showAdditionalFields, stopSendingPdftoHealthPlanDate: stopSendingPdftoHealthPlanDate);

                        _pcpResultExportServiceHelper.CreateCumulativeFileAndPost(incrementalFilePath, cumulativeFilePath, finalFilePath);

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

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(resultExportSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Custom Tag {0}  Message: {1} \n Stack Trace: {2} ", customTag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Message: {0} \n Stack Trace: {1} ", ex.Message, ex.StackTrace));
            }
        }
        public void PollForBiWeeklyMicroAlbuminFobt()
        {
            try
            {
                var timeOfDay = DateTime.Now;
                _logger.Info("Time of day : " + timeOfDay.ToString("HH:mm:ss"));

                if (!_settings.IsDevEnvironment && _runningDates.All(x => x != DateTime.Today.Day))
                {
                    _logger.Info("Report is generated only on 1st and 15th of the month");
                    return;
                }
                if (_accountId <= 0)
                {
                    _logger.Info("Account Id Not Provided");
                    return;
                }
                var account = _corporateAccountRepository.GetById(_accountId);
                if (account == null)
                {
                    _logger.Info("Account not exists");
                    return;
                }

                _logger.Info(string.Format("Generating Report for BiWeekly MicroAlbumin and IFobt"));

                var lastMonthDate = (DateTime.Today).AddMonths(-1);
                var endDate       = new DateTime(lastMonthDate.Year, lastMonthDate.Month, DateTime.DaysInMonth(lastMonthDate.Year, lastMonthDate.Month));
                var filter        = new BiWeeklyMicroAlbuminFobtReportModelFilter
                {
                    StartDate  = new DateTime(DateTime.Today.Year, 1, 1),
                    EndDate    = DateTime.Today,
                    AccountId  = _accountId,
                    CutOffDate = _cutoffDate
                };

                _logger.Info(string.Format("Generating Report for BiWeekly MicroAlbumin and IFobt"));
                if (lastMonthDate.Year < DateTime.Today.Year)
                {
                    filter = new BiWeeklyMicroAlbuminFobtReportModelFilter
                    {
                        AccountId = _accountId,
                        StartDate = new DateTime(lastMonthDate.Year, 1, 1),
                        EndDate   = endDate
                    };
                }

                _logger.Info("Start Date: " + filter.StartDate.ToShortDateString());
                _logger.Info("End Date: " + filter.EndDate.ToShortDateString());

                var dataGen = new ExportableDataGenerator <BiWeeklyMicroAlbuminFobtReportViewModel, BiWeeklyMicroAlbuminFobtReportModelFilter>(_biWeeklyMicroAlbuminFobtReportService.GetEventCustomerResultForReport, _logger);
                var model   = dataGen.GetData(filter);

                if (model != null && !model.Collection.IsNullOrEmpty())
                {
                    var exporter = ExportableDataGeneratorProcessManager <ViewModelBase, ModelFilterBase> .GetCsvExporter <BiWeeklyMicroAlbuminFobtReportViewModel>();

                    var path = string.Format(_biWeeklyReportPath, account.FolderName);
                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(path);

                    var reportfilePath = Path.Combine(path, string.Format("WellMed_Kit_Disbursement_{0}.csv", DateTime.Now.ToString("yyyyMMdd")));
                    _logger.Info("File path : " + reportfilePath);
                    DirectoryOperationsHelper.DeleteFileIfExist(reportfilePath);
                    _baseExportableReportHelper.GenerateCsv(reportfilePath, exporter, model.Collection);

                    if (_sendReportToSftp && DirectoryOperationsHelper.IsFileExist(reportfilePath))
                    {
                        var sftpResultExportDirectory = _sftpPathForBiWeeklyMicroAlbuminFobtReport;

                        var processFtp = new ProcessFtp(_logger, _sftpHost, _sftpUserName, _sftpPassword);
                        processFtp.UploadSingleFile(reportfilePath, sftpResultExportDirectory, "");
                    }
                    _logger.Info("BiWeeklyMicroAlbuminFobt Report generation completed");
                }
                else
                {
                    _logger.Info("No customer found for Report");
                }
            }
            catch (Exception exception)
            {
                _logger.Error("Some error occurred ");
                _logger.Error("Message:  " + exception.Message);
                _logger.Error("Stack Trace:  " + exception.StackTrace);
            }
        }
        public void Parse()
        {
            try
            {
                if (_settings.StopHansonResultParse)
                {
                    _logger.Info("Service has stop. If want enable please check setting.");
                    return;
                }

                _logger.Info("\n\n\n====================================== Blood Result Parsing - " + Directory.GetParent(_bloodResultFolderLocation).Name + "\\" + (new DirectoryInfo(_bloodResultFolderLocation)).Name + " ===========================================\n");

                if (!Directory.Exists(_bloodResultFolderLocation))
                {
                    _logger.Info("Blood Result Parsing - Folder does not exist at location" + _bloodResultFolderLocation);
                    return;
                }
                var files = Directory.GetFiles(_bloodResultFolderLocation).Where(x => x.Contains("csv"));

                if (files.IsNullOrEmpty())
                {
                    _logger.Info("Blood Result Parsing - No File Found For Parsing at " + _bloodResultFolderLocation);
                    return;
                }


                if (!Directory.Exists(_bloodResultArchiveFolderLocation))
                {
                    Directory.CreateDirectory(_bloodResultArchiveFolderLocation);
                }


                var mediaLocation         = _mediaRepository.GetBloodResultParseMediaLocation();
                var archiveMediaLocation  = Path.Combine(mediaLocation.PhysicalPath, "Archive", DateTime.Today.ToString("MMddyyyy"));
                var failedRecordsLocation = Path.Combine(mediaLocation.PhysicalPath, "Failed", DateTime.Today.ToString("MMddyyyy"));

                foreach (var file in files)
                {
                    _logger.Info("Blood Result Parsing - Files: " + file + " Started");

                    var fileName = Path.GetFileName(file);
                    if (string.IsNullOrEmpty(fileName))
                    {
                        return;
                    }
                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(archiveMediaLocation);

                    var mediaFilePath = Path.Combine(mediaLocation.PhysicalPath, fileName);

                    DirectoryOperationsHelper.DeleteFileIfExist(mediaFilePath);

                    _logger.Info("Moving file to media location : " + mediaFilePath);
                    DirectoryOperationsHelper.Move(file, mediaFilePath);
                    _logger.Info("File moved : " + fileName);

                    var newFileName = Path.GetFileNameWithoutExtension(file) + "_" + DateTime.Now.ToString("MMddyyyhhmmss");

                    var parseLogger = _logManager.GetLogger(newFileName);

                    var bloodResultParser     = new BloodResultParser(mediaFilePath, parseLogger, _csvReader, _logManager);
                    var customerScreeningData = bloodResultParser.Parse();

                    _logger.Info("Blood Result Parsing - Files: " + file + " Completed");

                    if (customerScreeningData.IsNullOrEmpty())
                    {
                        DirectoryOperationsHelper.Copy(mediaFilePath, Path.Combine(_bloodResultArchiveFolderLocation, newFileName + Path.GetExtension(mediaFilePath)));
                        DirectoryOperationsHelper.Move(mediaFilePath, Path.Combine(archiveMediaLocation, newFileName + Path.GetExtension(mediaFilePath)));
                        continue;
                    }

                    Save(customerScreeningData, UploadedBy);

                    DirectoryOperationsHelper.Copy(mediaFilePath, Path.Combine(archiveMediaLocation, newFileName + Path.GetExtension(mediaFilePath)));
                    _logger.Info("Blood Result Parsing - Files: " + file + " copied on Archive location");

                    DirectoryOperationsHelper.Move(mediaFilePath, _bloodResultArchiveFolderLocation + newFileName + Path.GetExtension(mediaFilePath));
                    _logger.Info("Blood Result Parsing - Files: " + file + " moved on Client location");

                    var resultLog = bloodResultParser.BloodTestResultParserLogs;

                    if (!resultLog.IsNullOrEmpty() && resultLog.Any(x => !x.IsSuccessful))
                    {
                        var failedFileName        = newFileName + "_ErrorLog.csv";
                        var failedRecordsFilePath = Path.Combine(failedRecordsLocation, failedFileName);

                        _logger.Info("Creating error log file : " + failedFileName);
                        DirectoryOperationsHelper.CreateDirectoryIfNotExist(failedRecordsLocation);
                        UpdateFailedRecords(failedRecordsFilePath, resultLog.Where(x => !x.IsSuccessful));

                        _logger.Info("Moving error log file to archive location.");
                        DirectoryOperationsHelper.Copy(failedRecordsFilePath, Path.Combine(_bloodResultArchiveFolderLocation, failedFileName));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Blood Result parsing: " + ex.Message + "\n" + ex.StackTrace, ex);
            }
        }
示例#6
0
        public void PollForNonTargetableCustomer()
        {
            try
            {
                var timeOfDay = DateTime.Now;
                _logger.Info("Time of day : " + timeOfDay.ToString("HH:mm:ss"));

                if (!_settings.IsDevEnvironment && _runningDate != DateTime.Today.Day)
                {
                    _logger.Info("Report is generated only in 1st week of the month");
                    return;
                }
                if (_accountId <= 0)
                {
                    _logger.Info("Account Id Not Provided");
                    return;
                }
                var account = _corporateAccountRepository.GetById(_accountId);
                if (account == null)
                {
                    _logger.Info("Account not exists");
                    return;
                }

                _logger.Info(string.Format("Generating Report for Non Target-able Report"));
                var lastMonthDate = (DateTime.Today).AddMonths(-1);

                var endDate = new DateTime(lastMonthDate.Year, lastMonthDate.Month, DateTime.DaysInMonth(lastMonthDate.Year, lastMonthDate.Month));
                var filter  = new NonTargetableReportModelFilter
                {
                    AccountId = _accountId,
                    StartDate = new DateTime(DateTime.Today.Year, 1, 1),
                    EndDate   = endDate
                };

                if (lastMonthDate.Year < DateTime.Today.Year)
                {
                    filter = new NonTargetableReportModelFilter
                    {
                        AccountId = _accountId,
                        StartDate = new DateTime(lastMonthDate.Year, 1, 1),
                        EndDate   = endDate
                    };
                }

                var eventScheduleModelFilter = new EventScheduleListModelFilter
                {
                    AccountId = _accountId,
                    FromDate  = filter.StartDate,
                    ToDate    = filter.EndDate
                };
                var stateIds = _eventRepository.GetEventStateByAccountId(eventScheduleModelFilter);
                if (stateIds.IsNullOrEmpty())
                {
                    _logger.Info("No State found for Wellmed");
                }
                var states = _stateRepository.GetStates(stateIds);

                foreach (var state in states)
                {
                    try
                    {
                        _logger.Info("Generating Report for State: " + state.Name);

                        var dataGen = new ExportableDataGenerator <NonTargetableReportModel, NonTargetableReportModelFilter>(_nonTargetableReportService.GetCustomersForNonTargetableService, _logger);
                        filter.StateId = state.Id;
                        var model = dataGen.GetData(filter);

                        if (model != null && !model.Collection.IsNullOrEmpty())
                        {
                            var exporter = ExportableDataGeneratorProcessManager <ViewModelBase, ModelFilterBase> .GetCsvExporter <NonTargetableReportModel>();

                            var path           = string.Format(_nonTargetableReportPath, account.FolderName);
                            var reportfilePath = Path.Combine(path, state.Name);

                            DirectoryOperationsHelper.CreateDirectoryIfNotExist(reportfilePath);
                            reportfilePath = Path.Combine(reportfilePath, string.Format("WellMed_NonTargetable_{0}.csv", DateTime.Now.ToString("yyyyMM")));
                            _logger.Info("File path : " + reportfilePath);

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

                            if (_sendReportToSftp && DirectoryOperationsHelper.IsFileExist(reportfilePath))
                            {
                                _logger.Info("Starting to post non targetable report on sftp for StateId: " + state.Id + " State: " + state.Name);

                                var sftpResultExportDirectory = string.Format(_sftpPathForNonTargetableReport, state.Name);
                                var processFtp = new ProcessFtp(_logger, _sftpHost, _sftpUserName, _sftpPassword);
                                processFtp.UploadSingleFile(reportfilePath, sftpResultExportDirectory, "");

                                _logger.Info("Non targetable report posted on sftp for StateId: " + state.Id + " State: " + state.Name);
                            }
                            _logger.Info("Non targetable Report generation completed for StateId: " + state.Id + " State: " + state.Name);
                        }
                        else
                        {
                            _logger.Info("No customer found for StateId: " + state.Id + " State: " + state.Name);
                        }
                    }
                    catch (Exception exception)
                    {
                        _logger.Error("Error occurred during generation of report for StateId: " + state.Id);
                        _logger.Error("Message:  " + exception.Message);
                        _logger.Error("Stack Trace:  " + exception.StackTrace);
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.Error("Some error occurred ");
                _logger.Error("Message:  " + exception.Message);
                _logger.Error("Stack Trace:  " + exception.StackTrace);
            }
        }
示例#7
0
        public void PollGiftCertificateWellmedReport()
        {
            try
            {
                var wellmedFlAccountId = _settings.WellmedAccountId;
                var wellmedTxAccountId = _settings.WellmedTxAccountId;

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

                var corporateAccounts = _corporateAccountRepository.GetByIds(giftCertificateWellmedAccountIds);

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

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

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

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

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

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

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

                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationFoler);

                    var lastReportRunDate = toDate.AddDays(-7);

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

                        GenerateReport(destinationFoler, fromDate, toforPreviousYearDate, account, folderName);
                        GenerateReport(destinationFoler, toDate.GetFirstDateOfYear(), toDate, account, folderName);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.StackTrace);
            }
        }
        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));
            }
        }
示例#9
0
        public void ResultExport()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }

                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

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

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

                        var customSettings = _customSettingManager.Deserialize(resultExportSettings);

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

                        var toDate = DateTime.Now;

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

                        string[] showHiddenColumns = new string[1];

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

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

                        DirectoryOperationsHelper.CreateDirectoryIfNotExist(optumResultExportDownloadPath);

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

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

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

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

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(resultExportSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Account Id {0} and account Tag {1}  Message: {2} \n Stack Trace: {3} ", account.Id, account.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Message: {0} \n Stack Trace: {1} ", ex.Message, ex.StackTrace));
            }
        }
示例#10
0
        public IEnumerable <EventCustomerScreeningAggregate> Parse()
        {
            var eventCustomerAggregates = new List <EventCustomerScreeningAggregate>();

            var directoryPath = GetFolderPathfor(_resultOutputPath);

            if (string.IsNullOrEmpty(directoryPath))
            {
                return(null);
            }

            foreach (var filePath in DirectoryOperationsHelper.GetFiles(directoryPath))
            {
                if (Path.GetExtension(filePath).ToLower().Contains("pdf"))
                {
                    _logger.Info("Parsing file : " + filePath);
                    var  fileName = Path.GetFileName(filePath);
                    bool isSpiro  = false;
                    var  fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
                    isSpiro = fileNameWithoutExtension.ToLower().EndsWith(SpiroFilePrefix);


                    var searchPattern = fileName.Substring(0, GetIndexOfNthOccurence(fileName, '_', 5)) + "*" + (isSpiro ? "_spiro.pdf" : "_ecg.pdf");

                    var versionedFiles = DirectoryOperationsHelper.GetFiles(directoryPath, searchPattern).Select(Path.GetFileName);;

                    var latestVersion = versionedFiles.OrderByDescending(x => x).First();

                    if (Path.GetFileName(filePath) != latestVersion)
                    {
                        _logger.Info("A more recent version of this file is present : " + latestVersion);
                        continue;
                    }

                    var customerIdString = fileName.IndexOf("_") > 0 ? fileName.Substring(0, fileName.IndexOf("_")) : fileName;

                    long customerId;

                    if (!long.TryParse(customerIdString, out customerId))
                    {
                        _logger.Info("Customer ID not found on Pdf file : " + filePath);
                        continue;
                    }

                    if (!isSpiro)
                    {
                        bool isEkgTestPurchasedByCustomer        = _testResultService.IsTestPurchasedByCustomer(_eventId, customerId, (long)TestType.EKG);
                        bool isAwvEkgTestPurchasedByCustomer     = _testResultService.IsTestPurchasedByCustomer(_eventId, customerId, (long)TestType.AwvEkg);
                        bool isAwvEkgIppeTestPurchasedByCustomer = _testResultService.IsTestPurchasedByCustomer(_eventId, customerId, (long)TestType.AwvEkgIPPE);

                        try
                        {
                            if (!isEkgTestPurchasedByCustomer && !isAwvEkgTestPurchasedByCustomer && !isAwvEkgIppeTestPurchasedByCustomer)
                            {
                                _logger.Info("EKG/ECG is not availed by CustomerId[" + customerId + "].\n");
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Info("EKG/ECG is not availed by CustomerId[" + customerId + "]. Exception Caused.\n Message: " + ex.Message + ".\t Stack Trace:" + ex.StackTrace);
                            continue;
                        }

                        try
                        {
                            TestResult testResult = null;
                            var        testType   = TestType.EKG;

                            if (isAwvEkgIppeTestPurchasedByCustomer) //&& IsEkgIppeFile
                            {
                                testType = TestType.AwvEkgIPPE;
                            }
                            else if (isAwvEkgTestPurchasedByCustomer)
                            {
                                testType = TestType.AwvEkg;
                            }

                            var folderToSaveImage = _mediaRepository.GetResultMediaFileLocation(customerId, _eventId).PhysicalPath;

                            var resultMedia = GetMediaFromPdfFile(filePath, folderToSaveImage, testType.ToString());
                            resultMedia.ReadingSource = ReadingSource.Automatic;

                            if (resultMedia != null)
                            {
                                switch (testType)
                                {
                                case TestType.EKG:
                                    testResult = new EKGTestResult
                                    {
                                        ResultImage = resultMedia
                                    };
                                    break;

                                case TestType.AwvEkg:
                                    testResult = new AwvEkgTestResult
                                    {
                                        ResultImage = resultMedia
                                    };
                                    break;

                                case TestType.AwvEkgIPPE:
                                    testResult = new AwvEkgIppeTestResult
                                    {
                                        ResultImage = resultMedia
                                    };
                                    break;
                                }

                                _resultParserHelper.AddTestResulttoEventCustomerAggregate(eventCustomerAggregates, _eventId, customerId, testResult);
                                _resultParserHelper.AddResultArchiveLog(string.Empty, testType, customerId, MedicalEquipmentTag.CardioCard);

                                _logger.Info(string.Concat("\nParsing succeeded for EKG  for Customer Id: ", customerId, "\n"));
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("System Failure! Message: " + ex.Message + "\n\t" + ex.StackTrace);
                            _resultParserHelper.AddResultArchiveLog(ex.Message, isAwvEkgIppeTestPurchasedByCustomer ? TestType.AwvEkgIPPE : isAwvEkgTestPurchasedByCustomer ? TestType.AwvEkg : TestType.EKG, customerId, MedicalEquipmentTag.CardioCard, false);
                        }
                    }
                    else if (isSpiro)
                    {
                        bool isSpiroTestPurchasedByCustomer    = _testResultService.IsTestPurchasedByCustomer(_eventId, customerId, (long)TestType.Spiro);
                        bool isAwvSpiroTestPurchasedByCustomer = _testResultService.IsTestPurchasedByCustomer(_eventId, customerId, (long)TestType.AwvSpiro);

                        try
                        {
                            if (!isSpiroTestPurchasedByCustomer && !isAwvSpiroTestPurchasedByCustomer)
                            {
                                _logger.Info("SPIRO/AWVSPIRO is not availed by CustomerId[" + customerId + "].\n");
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Info("SPIRO/AWVSPIRO is not availed by CustomerId[" + customerId + "]. Exception Caused.\n Message: " + ex.Message + ".\t Stack Trace:" + ex.StackTrace);
                            continue;
                        }

                        try
                        {
                            TestResult testResult = null;
                            var        testType   = TestType.Spiro;

                            if (isAwvSpiroTestPurchasedByCustomer)
                            {
                                testType = TestType.AwvSpiro;
                            }

                            var folderToSaveImage = _mediaRepository.GetResultMediaFileLocation(customerId, _eventId).PhysicalPath;

                            var resultMedia = GetMediaFromPdfFile(filePath, folderToSaveImage, testType.ToString(), false);
                            resultMedia.ReadingSource = ReadingSource.Automatic;

                            if (resultMedia != null)
                            {
                                switch (testType)
                                {
                                case TestType.Spiro:
                                    testResult = new SpiroTestResult
                                    {
                                        ResultImage = resultMedia
                                    };
                                    break;

                                case TestType.AwvSpiro:
                                    testResult = new AwvSpiroTestResult
                                    {
                                        ResultImage = resultMedia
                                    };
                                    break;
                                }

                                _resultParserHelper.AddTestResulttoEventCustomerAggregate(eventCustomerAggregates, _eventId, customerId, testResult);
                                _resultParserHelper.AddResultArchiveLog(string.Empty, testType, customerId, MedicalEquipmentTag.CardioCard);

                                _logger.Info(string.Concat("\nParsing succeeded for SPIRO/AWVSPIRO  for Customer Id: ", customerId, "\n"));
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("System Failure! Message: " + ex.Message + "\n\t" + ex.StackTrace);
                            _resultParserHelper.AddResultArchiveLog(ex.Message, isSpiroTestPurchasedByCustomer ? TestType.Spiro : TestType.AwvSpiro, customerId, MedicalEquipmentTag.CardioCard, false);
                        }
                    }
                }
            }
            return(eventCustomerAggregates);
        }
示例#11
0
        public void PollForCustomerEligibilityUpload()
        {
            try
            {
                if (_settings.StopCustomerEligibilityUpload)
                {
                    _logger.Info("Customer Eligibility Upload Polling Agent stopped @:" + DateTime.Now);
                    return;
                }

                _logger.Info("Entering Customer Eligibility Upload Polling Agent @:" + DateTime.Now);

                var sftpFileLocation = _settings.CustomerEligibilityUploadSftpPath;
                var mediaLocation    = _mediaRepository.GetCustomerEligibilityUploadFolderLocation();

                var archiveFolder = Path.Combine(mediaLocation.PhysicalPath, "Archive", DateTime.Today.ToString("yyyyMMdd"));
                var failedFolder  = Path.Combine(mediaLocation.PhysicalPath, "Failed", DateTime.Today.ToString("yyyyMMdd"));

                var getFilesFromSftp = DirectoryOperationsHelper.GetFiles(sftpFileLocation, "*.txt").Where(x => x.ToLower().Contains("outtake") && x.ToLower().Contains("eligibility"));

                if (getFilesFromSftp.IsNullOrEmpty())
                {
                    _logger.Info("No files found for parsing.");
                    return;
                }

                DirectoryOperationsHelper.CreateDirectoryIfNotExist(archiveFolder);
                DirectoryOperationsHelper.CreateDirectoryIfNotExist(failedFolder);

                var timeStamp = DateTime.Now.ToString("yyyyMMddhhmmss");

                foreach (var file in getFilesFromSftp)
                {
                    var fileName = Path.GetFileNameWithoutExtension(file);
                    MoveFile(file, Path.Combine(mediaLocation.PhysicalPath, fileName + "_" + timeStamp + ".txt"));
                }

                var filesToParse = DirectoryOperationsHelper.GetFiles(mediaLocation.PhysicalPath, "*.txt");
                _logger.Info("Number of files to Parse:" + filesToParse.Count());

                foreach (var file in filesToParse)
                {
                    var fileName = Path.GetFileName(file);
                    try
                    {
                        var patientData = _pipeDelimitedReportHelper.ReadWithTextQualifier(file);

                        var columns            = patientData.Columns.Cast <DataColumn>().Select(x => x.ColumnName.ToLower()).ToArray();
                        var missingColumnNames = _corporateUploadHelper.CheckAllCustomerEligibilityUploadColumnExist(columns);

                        if (!string.IsNullOrEmpty(missingColumnNames))
                        {
                            _logger.Info("Column Name(" + missingColumnNames + ") missing in file(" + fileName + ")");
                            MoveFile(file, Path.Combine(failedFolder, fileName));
                            continue;
                        }

                        var recordsInFile = patientData.Rows.Count;
                        if (recordsInFile == 0)
                        {
                            _logger.Info("No record found in " + fileName);
                            MoveFile(file, Path.Combine(archiveFolder, fileName));
                            continue;
                        }
                        _logger.Info("Parsing file: " + fileName);
                        _logger.Info("Total number of records in file: " + recordsInFile);

                        var failedRecords = new List <CustomerEligibilityUploadViewModel>();

                        var parseEligibilityData = ParseEligibilityData(patientData.AsEnumerable(), failedRecords);

                        if (parseEligibilityData.Any())
                        {
                            foreach (var customerEligibility in parseEligibilityData)
                            {
                                try
                                {
                                    _logger.Info("Getting customer for AcesId: " + customerEligibility.AcesId);
                                    List <Customer> customers   = null;
                                    var             errorMesage = string.Empty;

                                    if (!string.IsNullOrWhiteSpace((customerEligibility.AcesId)) || !string.IsNullOrWhiteSpace(customerEligibility.MemberId))
                                    {
                                        if (!string.IsNullOrWhiteSpace(customerEligibility.AcesId))
                                        {
                                            customers = _customerRepository.GetCustomersByAcesId(customerEligibility.AcesId);

                                            if (customers.IsNullOrEmpty())
                                            {
                                                errorMesage = "Customer not found for AcesId: " + customerEligibility.AcesId;
                                                _logger.Info(errorMesage);
                                            }
                                        }
                                        else
                                        {
                                            errorMesage = "AcesId not provided for Member Id: " + customerEligibility.MemberId;
                                            _logger.Info(errorMesage);
                                        }

                                        if (customers.IsNullOrEmpty())
                                        {
                                            if (!string.IsNullOrWhiteSpace(customerEligibility.MemberId))
                                            {
                                                customers = _customerRepository.GetCustomersByMemberId(customerEligibility.MemberId);

                                                if (customers.IsNullOrEmpty())
                                                {
                                                    errorMesage = errorMesage + ", " + "Customer not found for Member ID: " + customerEligibility.MemberId;
                                                    _logger.Info(errorMesage);
                                                }
                                            }
                                            else
                                            {
                                                errorMesage = errorMesage + " , " + "Member Id not provided for AcesId: " + customerEligibility.AcesId;
                                                _logger.Info(errorMesage);
                                            }
                                        }

                                        if (customers.IsNullOrEmpty())
                                        {
                                            customerEligibility.Error = errorMesage;
                                            failedRecords.Add(customerEligibility);

                                            _logger.Info("Record not parsed:  " + errorMesage);
                                            continue;
                                        }

                                        bool?eligibility = null;

                                        if (customerEligibility.Eligibility.ToLower() == CustomerEligibilityYes.ToLower())
                                        {
                                            eligibility = true;
                                        }

                                        else if (customerEligibility.Eligibility.ToLower() == CustomerEligibilityNo.ToLower())
                                        {
                                            eligibility = false;
                                        }

                                        int eligibilityYear = Convert.ToInt32(customerEligibility.EligibilityYear);

                                        foreach (var customer in customers)
                                        {
                                            _customerEligibilityService.Save(customer.CustomerId, eligibilityYear, eligibility, OrgRoleId, _logger);
                                            _logger.Info("Customer Eligibility inserted successfully for CustomerID: " + customer.CustomerId);
                                        }
                                    }
                                    else
                                    {
                                        errorMesage = "Aces Id or Member Id not provided ";
                                        customerEligibility.Error = errorMesage;
                                        failedRecords.Add(customerEligibility);

                                        _logger.Info("Record not parsed " + errorMesage);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    customerEligibility.Error = "Some error occurred while saving record.";
                                    failedRecords.Add(customerEligibility);
                                    _logger.Error(string.Format("Error occurred while saving record for AcesId: {0}.\nMessage: {1}\n\tStackTrace: {2}", customerEligibility.AcesId, ex.Message, ex.StackTrace));
                                }
                            }
                        }
                        CreateFailedUploadFile(fileName, failedFolder, failedRecords);
                        MoveFile(file, Path.Combine(archiveFolder, fileName));
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Error occurred while processing the {0}.\nMessage: {1}\n\tStackTrace: {2}", file, ex.Message, ex.StackTrace));

                        MoveFile(file, Path.Combine(failedFolder, fileName));
                    }
                }
                _logger.Info("File parsing completed @ " + DateTime.Now);

                try
                {
                    _logger.Info("Copying failed file at SFTP");
                    var failedFiles = DirectoryOperationsHelper.GetFiles(failedFolder, "*.txt");
                    if (failedFiles.IsNullOrEmpty())
                    {
                        _logger.Info("No failed files found to copy at SFTP.");
                        return;
                    }

                    _logger.Info("Creating failed folder at SFTP " + sftpFileLocation);
                    var sftpFailedFolder = Path.Combine(sftpFileLocation, "FailedCustomerRecords", DateTime.Today.ToString("yyyyMMdd"));
                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(sftpFailedFolder);

                    foreach (var file in failedFiles)
                    {
                        var failedFileName = Path.GetFileName(file);
                        try
                        {
                            DirectoryOperationsHelper.Copy(file, Path.Combine(sftpFailedFolder, failedFileName));
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(string.Format("Copying faield file not succeed for {0}. \nException Message: {1}\n\tStackTrace:{2}", failedFileName, ex.Message, ex.StackTrace));
                        }
                    }
                    _logger.Info("All failed files copied at " + sftpFailedFolder + " location.");
                }
                catch (Exception ex)
                {
                    _logger.Error(string.Format("Exception occurred during copying failed file at SFTP. \nException Message: {0}\n\tStackTrace:{1}", ex.Message, ex.StackTrace));
                    return;
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Exception occurred during execution of servcie. \nException Message: {0}\n\tStackTrace:{1}", ex.Message, ex.StackTrace));
                return;
            }
        }