Beispiel #1
0
        private void CopyMediaFile(long customerId, long eventId, IEnumerable <string> mediaFiles)
        {
            var mediaPath       = _mediaRepository.GetResultMediaFileLocation(customerId, eventId).PhysicalPath;
            var destinationPath = Path.Combine(_settings.SendTestMediaFilesClientLocation, eventId.ToString(), customerId.ToString());

            DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationPath);
            DirectoryOperationsHelper.DeleteFiles(destinationPath);

            foreach (var file in mediaFiles)
            {
                var sourceFileName = Path.Combine(mediaPath, file);
                if (File.Exists(sourceFileName))
                {
                    File.Copy(sourceFileName, Path.Combine(destinationPath, file));
                    _logger.Info("Media file(" + file + ") successfully copied on location @" + destinationPath + " for Customer Id: " + customerId + " Event Id: " + eventId);
                }
                else
                {
                    _logger.Info("Media file(" + file + ") does not exist on Media file Location for Customer Id: " + customerId + " Event Id: " + eventId);
                }
            }
        }
Beispiel #2
0
        public void CreateCsvForFileShared(IEnumerable <CustomerInfo> customersInfo, string folderPath, string fileName)
        {
            _logger.Info("Creating csv file..");

            DirectoryOperationsHelper.CreateDirectoryIfNotExist(folderPath);

            try
            {
                var years = customersInfo.Where(x => x.EventDate.HasValue).Select(x => x.EventDate.Value.Year).Distinct();

                foreach (var year in years)
                {
                    var tempfileName = fileName + "_" + year + ".csv";

                    var destinationFileName = Path.Combine(folderPath, tempfileName);
                    //if (year < DateTime.Today.Year && DirectoryOperationsHelper.IsFileExist(destinationFileName))
                    //{
                    //    continue;
                    //}

                    DirectoryOperationsHelper.DeleteFileIfExist(destinationFileName);

                    _logger.Info("Count Records " + customersInfo.Count());

                    _logger.Info("destination Path: " + destinationFileName);

                    WriteCsv(destinationFileName, customersInfo.Where(x => x.EventDate.HasValue && x.EventDate.Value.Year == year));
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Some Error occurred while Creating Csv log:");
                _logger.Error("Message:" + ex.Message);
                _logger.Error("Stack trace:" + ex.StackTrace);
            }

            _logger.Info("Created csv file..");
        }
        private void CopyMediaFile(string sourceFileName, string destinationPath, string newFileName)
        {
            try
            {
                DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationPath);

                if (DirectoryOperationsHelper.IsFileExist(sourceFileName))
                {
                    var destinationFile = Path.Combine(destinationPath, newFileName);
                    DirectoryOperationsHelper.CopyWithReplace(sourceFileName, destinationFile);

                    _logger.Info("Media file ( " + sourceFileName + " ) successfully copied with new Name " + newFileName + " on location " + destinationPath);
                }
                else
                {
                    _logger.Info("Media file ( " + sourceFileName + " ) does not exist on Media file Location");
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Message: Media file ( " + sourceFileName + " ) does not exist on Media file Location. Exception : " + ex.Message);
                _logger.Error("StackTrace:" + ex.StackTrace);
            }
        }
Beispiel #4
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);
            }
        }
Beispiel #5
0
        private void CreateCrossWalkFile(string csvFilePath, IEnumerable <AnthemPdfCrossWalkVeiwModel> modelData)
        {
            try
            {
                if (modelData.IsNullOrEmpty())
                {
                    _logger.Info("No Data found to generate crosswalk file ");
                    return;
                }
                try
                {
                    DirectoryOperationsHelper.DeleteFiles(csvFilePath, "CrosswalkFile_*.csv");
                }
                catch (Exception exception)
                {
                    _logger.Error(" While deleting old files");
                    _logger.Error("message: " + exception);
                    _logger.Error("stack Trace: " + exception.StackTrace);
                }

                DirectoryOperationsHelper.CreateDirectoryIfNotExist(_crosswalkFilePath);
                DirectoryOperationsHelper.CreateDirectoryIfNotExist(csvFilePath);

                var filePath = Path.Combine(_crosswalkFilePath, "CrosswalkFile_" + _crosswalkFileYear + ".csv");

                bool createHeaderRow = !DirectoryOperationsHelper.IsFileExist(filePath);

                _logger.Info("File Path: " + filePath);

                if (createHeaderRow)
                {
                    _logger.Info("Header info being created");
                }

                var csvFileName = Path.Combine(csvFilePath, "CrosswalkFile_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv");

                using (var streamWriter = new StreamWriter(filePath, append: !createHeaderRow))
                {
                    var members = (typeof(AnthemPdfCrossWalkVeiwModel)).GetMembers();

                    if (createHeaderRow)
                    {
                        var header = new List <string>();
                        foreach (var memberInfo in members)
                        {
                            if (memberInfo.MemberType != MemberTypes.Property)
                            {
                                continue;
                            }

                            var propInfo = (memberInfo as PropertyInfo);
                            if (propInfo != null)
                            {
                                if (propInfo.PropertyType == typeof(FeedbackMessageModel))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                continue;
                            }

                            string propertyName = memberInfo.Name;
                            bool   isHidden     = false;

                            var attributes = propInfo.GetCustomAttributes(false);
                            if (!attributes.IsNullOrEmpty())
                            {
                                foreach (var attribute in attributes)
                                {
                                    if (attribute is HiddenAttribute)
                                    {
                                        isHidden = true;
                                        break;
                                    }
                                    if (attribute is DisplayNameAttribute)
                                    {
                                        propertyName = (attribute as DisplayNameAttribute).DisplayName;
                                    }
                                }
                            }

                            if (isHidden)
                            {
                                continue;
                            }

                            header.Add(propertyName);
                        }

                        streamWriter.Write(string.Join(",", header.ToArray()) + Environment.NewLine);
                    }

                    var sanitizer = new CSVSanitizer();
                    foreach (var model in modelData)
                    {
                        var values = new List <string>();
                        foreach (var memberInfo in members)
                        {
                            if (memberInfo.MemberType != MemberTypes.Property)
                            {
                                continue;
                            }

                            var propInfo = (memberInfo as PropertyInfo);
                            if (propInfo != null)
                            {
                                if (propInfo.PropertyType == typeof(FeedbackMessageModel))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                continue;
                            }


                            bool            isHidden  = false;
                            FormatAttribute formatter = null;

                            var attributes = propInfo.GetCustomAttributes(false);
                            if (!attributes.IsNullOrEmpty())
                            {
                                foreach (var attribute in attributes)
                                {
                                    if (attribute is HiddenAttribute)
                                    {
                                        isHidden = true;
                                        break;
                                    }
                                    if (attribute is FormatAttribute)
                                    {
                                        formatter = (FormatAttribute)attribute;
                                    }
                                }
                            }

                            if (isHidden)
                            {
                                continue;
                            }
                            var obj = propInfo.GetValue(model, null);
                            if (obj == null)
                            {
                                values.Add(string.Empty);
                            }
                            else if (formatter != null)
                            {
                                values.Add(formatter.ToString(obj));
                            }
                            else
                            {
                                values.Add(sanitizer.EscapeString(obj.ToString()));
                            }
                        }
                        streamWriter.Write(string.Join(",", values.ToArray()) + Environment.NewLine);
                    }

                    streamWriter.Close();

                    _logger.Info("crosswalk .csv has been created at following location: ");
                    _logger.Info(filePath);

                    if (DirectoryOperationsHelper.IsFileExist(filePath))
                    {
                        DirectoryOperationsHelper.DeleteFileIfExist(csvFileName);
                        DirectoryOperationsHelper.Copy(filePath, csvFileName);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("While Generating crosswalk file: message " + ex.Message + " stack trace:  " + ex.StackTrace);
            }
        }
Beispiel #6
0
        public void Parse()
        {
            try
            {
                _logger.Info("Running Loinc Crosswalk");

                if (!DirectoryOperationsHelper.CreateDirectoryIfNotExist(_settings.LoincCrosswalkPath))
                {
                    _logger.Info(string.Format("Folder could not be created. Please check path: {0} ", _settings.LoincCrosswalkPath));
                    return;
                }

                var loincMediaLocation = _mediaRepository.GetLoincMediaLocation();
                var archiveLocation    = _mediaRepository.GetLoincArchiveMediaLocation();

                var loincCrosswalkfiles = DirectoryOperationsHelper.GetFiles(_settings.LoincCrosswalkPath, "*.csv");
                if (loincCrosswalkfiles.IsNullOrEmpty())
                {
                    _logger.Info(string.Format("No csv file found at following location {0}", _settings.LoincCrosswalkPath));
                }
                else
                {
                    UploadLoincFiles(loincCrosswalkfiles, loincMediaLocation.PhysicalPath, (long)OutboundUploadType.LoincCrosswalk);
                }

                var uploadedFiles = _outboundUploadRepository.GetAllUploadedFilesByType((long)OutboundUploadType.LoincCrosswalk);
                if (uploadedFiles.IsNullOrEmpty())
                {
                    _logger.Info("No new files uploaded for Loinc Crosswalk.");
                    return;
                }

                foreach (var uploadedFile in uploadedFiles)
                {
                    try
                    {
                        var file = GetFile(uploadedFile.FileId);

                        if (!System.IO.File.Exists(loincMediaLocation.PhysicalPath + file.Path))
                        {
                            _logger.Info("File not found : " + loincMediaLocation.PhysicalPath + file.Path);
                            continue;
                        }

                        uploadedFile.StatusId       = (long)OutboundUploadStatus.Parsing;
                        uploadedFile.ParseStartTime = DateTime.Now;
                        _outboundUploadRepository.Save(uploadedFile);

                        _logger.Info("Importing File : " + file.Path);

                        var dataTable = _csvReader.CsvToDataTable(loincMediaLocation.PhysicalPath + file.Path, true, ",");

                        var csvStringBuilder = new StringBuilder();
                        csvStringBuilder.Append(LogHeader + Environment.NewLine);

                        long totalRows = 0, successRows = 0;

                        if (dataTable.Rows.Count == 0)
                        {
                            _logger.Info("No records found for file : " + loincMediaLocation.PhysicalPath + file.Path);
                            continue;
                        }
                        foreach (DataRow row in dataTable.Rows)
                        {
                            totalRows++;
                            var model    = GetLoincCrosswalk(row);
                            var errorRow = model.LoincNumber + "," + model.Component + "," + model.System + "," + model.MethodType + "," + model.VersionLastChanged + "," + model.DefinitionDescription + "," + model.Formula + model.Species
                                           + model.ExampleAnswers + "," + model.SurveyQuestionText + "," + model.SurveyQuestionSource + "," + model.UnitsRequired + "," + model.SubmittedUnits + "," + model.CdiscCommonTests + "," + model.Hl7FieldSubfieldId
                                           + model.ExternalCopyrightNotice + model.ExampleUnits + model.LongCommonName;

                            try
                            {
                                if (!model.IsEmpty())
                                {
                                    model.Year        = DateTime.Today.Year;
                                    model.DateCreated = DateTime.Now;
                                    model.UploadId    = uploadedFile.Id;
                                }
                                _loincCrosswalkRepository.Save(model);
                                successRows++;
                            }
                            catch (Exception ex)
                            {
                                _logger.Error(string.Format("Some Error Occurred Message: {0} \n stack Trace: {1}", ex.Message, ex.StackTrace));
                                csvStringBuilder.Append(errorRow + "," + ex.Message + Environment.NewLine);
                            }
                        }

                        if (successRows < totalRows)
                        {
                            var logFileName = file.Path + "_Log.csv";

                            var logFile = SaveLogFile(_settings.LoincCrosswalkPath + logFileName, csvStringBuilder);
                            uploadedFile.LogFileId = logFile.Id;
                        }

                        uploadedFile.SuccessUploadCount = successRows;
                        uploadedFile.FailedUploadCount  = totalRows - successRows;
                        uploadedFile.ParseEndTime       = DateTime.Now;
                        uploadedFile.StatusId           = successRows > 0 ? (long)OutboundUploadStatus.Parsed : (long)OutboundUploadStatus.ParseFailed;
                        _outboundUploadRepository.Save(uploadedFile);

                        if (successRows > 1)
                        {
                            System.IO.File.Move(loincMediaLocation.PhysicalPath + file.Path, archiveLocation.PhysicalPath + file.Path);
                            ((IFileRepository)_fileRepository).MarkasArchived(file.Id);
                        }
                    }
                    catch (Exception ex)
                    {
                        uploadedFile.StatusId = (long)OutboundUploadStatus.ParseFailed;
                        _outboundUploadRepository.Save(uploadedFile);
                        _logger.Error(string.Format("while Parsing File"));
                        _logger.Error("Ex Message" + ex.Message);
                        _logger.Error("Ex Stack Trace " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error while Parsing Loinc Crosswalk Files.");
                _logger.Error(ex);
            }
        }
Beispiel #7
0
        public void ResultExport()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }

                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

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

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

                        var customSettings = _customSettingManager.Deserialize(resultExportSettings);

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

                        var toDate = DateTime.Now;

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

                        string[] showHiddenColumns = new string[1];

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

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

                        DirectoryOperationsHelper.CreateDirectoryIfNotExist(optumResultExportDownloadPath);

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

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

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

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

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(resultExportSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Account Id {0} and account Tag {1}  Message: {2} \n Stack Trace: {3} ", account.Id, account.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Message: {0} \n Stack Trace: {1} ", ex.Message, ex.StackTrace));
            }
        }
        public void 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);
            }
        }
        private void GenerateReportForShortName(IEnumerable <CorporateAccount> accounts)
        {
            var distinctAcesClientShortName = accounts.Where(x => !string.IsNullOrWhiteSpace(x.AcesClientShortName)).Select(t => t.AcesClientShortName)
                                              .Distinct();

            foreach (var acesClientShortName in distinctAcesClientShortName)
            {
                var accountShortNamewise = accounts.Where(d => d.AcesClientShortName == acesClientShortName);

                if (!accountShortNamewise.IsNullOrEmpty())
                {
                    _logger.Info("starting for Shortname " + acesClientShortName);
                    var destinationFoler = _settings.UniversalProviderFilePath;

                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationFoler);
                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(_folderArchivedPath);

                    var fileNameWithoutExtention = acesClientShortName + "_Universal_Provider";
                    var fileName = fileNameWithoutExtention + ".txt";

                    var destinationFile = Path.Combine(destinationFoler, fileName);

                    if (DirectoryOperationsHelper.IsFileExist(destinationFile))
                    {
                        var archiveFileName = fileNameWithoutExtention + "_" + DateTime.Today.AddDays(-1).ToString("ddMMyyyy") + ".txt";
                        var archiveFilePath = Path.Combine(_folderArchivedPath, archiveFileName);
                        DirectoryOperationsHelper.DeleteFileIfExist(archiveFilePath);
                        DirectoryOperationsHelper.Move(destinationFile, archiveFilePath);
                    }

                    WriteCsvHeader(destinationFile);

                    foreach (var account in accountShortNamewise)
                    {
                        try
                        {
                            _logger.Info("starting for account " + account.Tag);

                            GenerateUniversalProviderList(account, destinationFile);

                            _logger.Info("completed for Account " + account.Tag);
                        }
                        catch (Exception exception)
                        {
                            _logger.Error("some error occurred while created Member List for Account " + account.Tag);
                            _logger.Error("Message: " + exception.Message);
                            _logger.Error("Stack Trace: " + exception.StackTrace);
                        }
                    }

                    if (DirectoryOperationsHelper.IsFileExist(destinationFile))
                    {
                        _logger.Info("Universal Provider Report generated : " + destinationFile);

                        DirectoryOperationsHelper.CreateDirectoryIfNotExist(_settings.UniversalProviderFileSftpPath);

                        _logger.Info("Deleting old files from SFTP.");
                        DirectoryOperationsHelper.DeleteFileIfExist(Path.Combine(_settings.UniversalProviderFileSftpPath, acesClientShortName + "_Universal_Provider.txt"));
                        _logger.Info("Old files deleted from SFTP.");

                        _logger.Info("Copying file to SFTP location : " + _settings.UniversalProviderFileSftpPath);
                        var sftpFilePath = Path.Combine(_settings.UniversalProviderFileSftpPath, fileName);
                        DirectoryOperationsHelper.Copy(destinationFile, sftpFilePath);
                        _logger.Info("File copied : " + sftpFilePath);
                    }
                }
            }
        }
Beispiel #10
0
        public void GetCustomersRecordAsPerShortName(string acesClientShortName, string folderPath)
        {
            try
            {
                var accountShortNamewise = _corporateAccount.Where(a => a.AcesClientShortName == acesClientShortName);

                var destinationFoler = folderPath;
                DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationFoler);
                _logger.Info("Directory Created: " + folderPath);

                var fileName        = acesClientShortName + "_HipToAcesCrosswalk_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt";
                var destinationFile = Path.Combine(folderPath, fileName);

                DirectoryOperationsHelper.DeleteFileIfExist(destinationFile);


                _logger.Info("starting for account AcesClientShortName " + acesClientShortName);

                foreach (var account in accountShortNamewise)
                {
                    if (string.IsNullOrWhiteSpace(account.Tag))
                    {
                        _logger.Info("Tag not available in this Account.");
                        continue;
                    }

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

                    var pageNumber = 1;

                    var filter = new HiptoAcesCrossWalkViewModelFilter
                    {
                        Tag = account.Tag,
                        CustomerOnlyWithAcesId = true,
                        OnlyEligibileCustomer  = true,
                        Year = DateTime.Today.Year
                    };

                    while (true)
                    {
                        int totalRecords = 0;

                        var customers = _customerRepository.GetCustomerForHiptoAcesCrossWalk(filter, pageNumber, PageSize, out totalRecords);
                        if (customers.IsNullOrEmpty())
                        {
                            _logger.Info("No customer found for Account Tag: " + account.Tag);
                            break;
                        }

                        var collection = new List <HiptoAcesCrossWalkViewModel>();

                        foreach (var customer in customers)
                        {
                            var model = _hiptoAcesCrossWalkFactory.Create(customer, account);
                            collection.Add(model);
                        }

                        if (!DirectoryOperationsHelper.IsFileExist(destinationFile))
                        {
                            WriteCsvHeader(destinationFile);
                        }

                        WriteCsv(collection, destinationFile);

                        _logger.Info((pageNumber * PageSize) + " out of " + totalRecords);

                        if ((pageNumber * PageSize) >= totalRecords)
                        {
                            break;
                        }

                        pageNumber++;
                    }
                }

                _logger.Info("File Generated Successfully at following Location: ");
                _logger.Info(destinationFile);
            }
            catch (Exception ex)
            {
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.StackTrace);
            }
        }
        public void GenerateHafAssessment(long eventId)
        {
            try
            {
                var eventLogger = _logManager.GetLogger("HealthAssessmentFormGenerator_" + eventId);
                eventLogger.Info("Generating HAF for Event Id: " + eventId);
                _pdfGenerator.PaperSize = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.PaperSize);

                try
                {
                    var eventCustomers = _eventCustomerRepository.GetbyEventId(eventId);

                    if (eventCustomers != null && eventCustomers.Any())
                    {
                        eventCustomers = eventCustomers.Where(ec => ec.AppointmentId.HasValue).ToArray();

                        if (eventCustomers != null && eventCustomers.Any())
                        {
                            eventLogger.Info("found EventCustomers Count: " + eventCustomers.Count());

                            var mediaLocation = _mediaRepository.GetMedicalHistoryMediaLocation(eventId);

                            DirectoryOperationsHelper.CreateDirectoryIfNotExist(mediaLocation.PhysicalPath);

                            DirectoryOperationsHelper.DeleteFiles(mediaLocation.PhysicalPath);
                            var eventData = _eventRepository.GetById(eventId);
                            var account   = _corporateAccountRepository.GetbyEventId(eventId);

                            var corporateSurveyPdf = "";
                            if (account != null && account.CaptureSurvey)
                            {
                                if (account.SurveyPdfFileId > 0)
                                {
                                    var surveyPdf = _fileRepository.GetById(account.SurveyPdfFileId);
                                    if (surveyPdf != null)
                                    {
                                        corporateSurveyPdf = _mediaRepository.GetCorporateSurveyPdfFolderLocation().PhysicalPath + surveyPdf.Path;
                                    }
                                }
                            }

                            var corporateCheckListPdf = "";
                            if (account != null && account.PrintCheckList && account.CheckListFileId > 0 && eventData.EventDate >= _settings.ChecklistChangeDate)
                            {
                                var checkListFilePdf = _fileRepository.GetById(account.CheckListFileId);
                                if (checkListFilePdf != null)
                                {
                                    corporateCheckListPdf = _mediaRepository.GetCorporateCheckListPdfFolderLocation().PhysicalPath + checkListFilePdf.Path;
                                }
                            }

                            var filesFocAttestation    = new[] { "" };
                            var mediaLocFocAttestation = _mediaRepository.GetUnlockEventsParseLocation(eventId);

                            if (account != null && account.Id == _settings.HcpNvAccountId)
                            {
                                if (DirectoryOperationsHelper.IsDirectoryExist(mediaLocFocAttestation.PhysicalPath))
                                {
                                    filesFocAttestation = Directory.GetFiles(mediaLocFocAttestation.PhysicalPath, "*.*");
                                    filesFocAttestation = filesFocAttestation.Where(fsd => !string.IsNullOrEmpty(fsd)).ToArray();
                                }
                            }
                            else
                            {
                                if (DirectoryOperationsHelper.IsDirectoryExist(mediaLocFocAttestation.PhysicalPath))
                                {
                                    filesFocAttestation = Directory.GetFiles(mediaLocFocAttestation.PhysicalPath, "*.pdf");
                                    filesFocAttestation = filesFocAttestation.Where(fsd => !string.IsNullOrEmpty(fsd)).ToArray();
                                }
                            }

                            var tempMediaLocation = _mediaRepository.GetTempMediaFileLocation();
                            var customers         = _customerRepository.GetCustomers(eventCustomers.Select(ec => ec.CustomerId).ToArray());

                            int index = 0;
                            foreach (var eventCustomer in eventCustomers)
                            {
                                eventLogger.Info(string.Format("Generating HAF for Event Id: {0} and Customer Id : {1} ", eventId, eventCustomer.CustomerId));
                                string url                = _settings.HealthAssessmentFormUrl + string.Format("?eventId={0}&customerId={1}&LoadLayout=false&showKynEditModel=true&bulkPrint=true&removeChache={2}", eventCustomer.EventId, eventCustomer.CustomerId, Guid.NewGuid());
                                var    customer           = customers.First(c => c.CustomerId == eventCustomer.CustomerId);
                                var    focAttestationFile = string.Empty;

                                if (account != null)
                                {
                                    var questFile = Path.Combine(_mediaRepository.GetQuestUploadMediaFileLocation().PhysicalPath, account.Tag + "_Quest.pdf");

                                    if (account.Id == _settings.WellmedAccountId || account.Id == _settings.WellmedTxAccountId)
                                    {
                                        var memberId = string.IsNullOrEmpty(customer.InsuranceId) ? "" : customer.InsuranceId.ToLower().Trim();
                                        focAttestationFile = filesFocAttestation.FirstOrDefault(fsd => !string.IsNullOrEmpty(fsd) && Path.GetFileNameWithoutExtension(fsd).ToLower().Trim() == memberId);
                                        eventLogger.Info(string.Format("focAttestationFile : {0}", focAttestationFile));

                                        var _files = new List <string>();

                                        if (!string.IsNullOrEmpty(focAttestationFile) && DirectoryOperationsHelper.IsFileExist(focAttestationFile))
                                        {
                                            eventLogger.Info(string.Format("focAttestationFile : First if {0}", focAttestationFile));
                                            _files.Add(focAttestationFile);
                                        }

                                        if (DirectoryOperationsHelper.IsFileExist(questFile))
                                        {
                                            eventLogger.Info(string.Format("focAttestationFile : 2nd if {0}", questFile));
                                            _files.Add(questFile);
                                        }

                                        if (!_files.IsNullOrEmpty())
                                        {
                                            if (_files.Count() > 1)
                                            {
                                                eventLogger.Info(string.Format("focAttestationFile : File Count {0}", _files.Count()));
                                                focAttestationFile = GetFocAttestationFileMerge(_files, focAttestationFile, eventLogger);
                                            }
                                            else
                                            {
                                                eventLogger.Info(string.Format("focAttestationFile : File[0] {0}", _files[0]));
                                                focAttestationFile = _files[0];
                                                eventLogger.Info(string.Format("focAttestationFile : Last {0}", focAttestationFile));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        focAttestationFile = GetFocAttestationFileForMht(filesFocAttestation, customer.CustomerId.ToString(), eventLogger);
                                    }
                                    //else if (account.Id == _settings.MolinaAccountId)
                                    //{
                                    //    var hicn = string.IsNullOrEmpty(customer.Hicn) ? "" : customer.Hicn.ToLower().Trim();
                                    //    focAttestationFile = filesFocAttestation.FirstOrDefault(fsd => !string.IsNullOrEmpty(fsd) && Path.GetFileNameWithoutExtension(fsd).ToLower().Trim() == hicn);
                                    //}
                                    //else if (account.Id == _settings.HcpNvAccountId)
                                    //{

                                    //}
                                    //else if (_settings.MonarchAccountIds.Contains(account.Id))
                                    //{
                                    //    var gmpi = string.IsNullOrEmpty(customer.AdditionalField4) ? "" : customer.AdditionalField4.ToLower().Trim();

                                    //    if (!string.IsNullOrEmpty(gmpi))
                                    //    {
                                    //        focAttestationFile = GetFocAttestationFile(filesFocAttestation, "_" + gmpi.ToLower(), focAttestationFile, eventLogger);
                                    //    }
                                    //}
                                    //else if (account.Id == _settings.AppleCareAccountId)
                                    //{
                                    //    focAttestationFile = GetFocAttestationFile(filesFocAttestation, customer.CustomerId.ToString(), focAttestationFile, eventLogger);
                                    //}
                                    //else if (account.Id == _settings.NammAccountId)
                                    //{
                                    //    focAttestationFile = GetFocAttestationFile(filesFocAttestation, customer.CustomerId.ToString(), focAttestationFile, eventLogger);
                                    //}
                                }

                                var focAttestationFilePath = string.Empty;
                                eventLogger.Info("focAttestationFile: " + focAttestationFile);

                                if (!string.IsNullOrEmpty(focAttestationFile))
                                {
                                    focAttestationFilePath = focAttestationFile;
                                }

                                var annualComprehensiveExamPdf  = string.Empty;
                                var memberInformationProfilePdf = string.Empty;

                                if (!string.IsNullOrEmpty(customer.Hicn))
                                {
                                    var fileNamePattern = customer.Hicn + (customer.Name != null ? "_" + customer.Name.LastName + "_" + customer.Name.FirstName : "");
                                    if (account != null && account.PrintAceForm)
                                    {
                                        try
                                        {
                                            var mediaLocationForAce = _mediaRepository.GetAceMipLocation(account.FolderName, fileNamePattern, "ACE");
                                            var aceFiles            = DirectoryOperationsHelper.GetFiles(mediaLocationForAce.PhysicalPath, fileNamePattern + "*_ACE.pdf");
                                            if (aceFiles.Any())
                                            {
                                                annualComprehensiveExamPdf = _pdfGenerator.ExtractPdfPagesFromEnd(aceFiles.First(), tempMediaLocation.PhysicalPath + "Ripped_" + customer.Hicn + "_ACE.pdf", NumberOfPagesToExtractFromAcePdf);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            eventLogger.Error(string.Format("Unable to attach ACE form to the bulk HAF for CustomerID : {0}\nMessage : {1}", customer.CustomerId, ex.Message));
                                        }
                                    }

                                    if (account != null && account.PrintMipForm)
                                    {
                                        try
                                        {
                                            var mediaLocationForMip = _mediaRepository.GetAceMipLocation(account.FolderName, fileNamePattern, "MIP");
                                            var mipFiles            = DirectoryOperationsHelper.GetFiles(mediaLocationForMip.PhysicalPath, fileNamePattern + "*_MIP.pdf");
                                            if (mipFiles.Any())
                                            {
                                                memberInformationProfilePdf = mipFiles.First();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            eventLogger.Error(string.Format("Unable to attach MIP to the bulk HAF for CustomerID : {0}\nMessage : {1}", customer.CustomerId, ex.Message));
                                        }
                                    }
                                }
                                var consentHeaderWithChecklistpdf = string.Empty;

                                if (!string.IsNullOrWhiteSpace(corporateCheckListPdf) && DirectoryOperationsHelper.IsFileExist(corporateCheckListPdf))
                                {
                                    var    tempPath         = _mediaRepository.GetTempMediaFileLocation();
                                    var    consentHeader    = Path.Combine(tempPath.PhysicalPath, Guid.NewGuid() + ".pdf");
                                    string consentHeaderUrl = _settings.ConsentHeaderFormUrl + string.Format("?eventId={0}&customerId={1}&removeChache={2}", eventCustomer.EventId, eventCustomer.CustomerId, Guid.NewGuid());
                                    _pdfGenerator.GeneratePdf(consentHeaderUrl, consentHeader);

                                    consentHeaderWithChecklistpdf = Path.Combine(tempPath.PhysicalPath, Guid.NewGuid() + ".pdf");
                                    var consentHeaderWithChecklistpdfArray = new string[] { consentHeader, corporateCheckListPdf };
                                    _pdfGenerator.Merge(consentHeaderWithChecklistpdf, consentHeaderWithChecklistpdfArray);
                                }


                                _pdfGenerator.GeneratePdfForHaf(url, mediaLocation.PhysicalPath + (++index).ToString("000.") + eventCustomer.CustomerId + ".pdf", corporateSurveyPdf, "", focAttestationFilePath, consentHeaderWithChecklistpdf,
                                                                annualComprehensiveExamPdf, memberInformationProfilePdf);
                            }

                            eventLogger.Info("Merging HAF for Event Id: " + eventId);
                            _pdfGenerator.GetPdffilesfromLocationandMergeintoOne(mediaLocation.PhysicalPath, mediaLocation.PhysicalPath + "Event_" + eventId + ".pdf");
                            _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed);

                            index = 0;

                            foreach (var eventCustomer in eventCustomers)
                            {
                                DirectoryOperationsHelper.Delete(mediaLocation.PhysicalPath + (++index).ToString("000.") + eventCustomer.CustomerId + ".pdf");
                            }
                        }
                        else
                        {
                            eventLogger.Info("No customer found with appointment attached with this event. Merging HAF for Event Id: " + eventId);
                            _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed);
                        }
                    }
                    else
                    {
                        eventLogger.Info("No customer found attached with this event. Merging HAF for Event Id: " + eventId);
                        _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed);
                    }
                }
                catch (Exception ex)
                {
                    _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, true, (long)GenerateHealthAssesmentFormStatus.Pending);
                    eventLogger.Error("\n" + ex.Message + "\n\t Stack Trace: " + ex.StackTrace);
                }
            }
            catch (Exception ex)
            {
                _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, true, (long)GenerateHealthAssesmentFormStatus.Pending);
                _logger.Error("\n" + ex.Message + "\n\t Stack Trace: " + ex.StackTrace);
            }
        }
        public void CreateZipFile()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);
                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Creating zip for accountId {0} and account tag {1}. ", account.Id, account.Tag));

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

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

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

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

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

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

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

                        var directoryToDeleteFrom = new DirectoryInfo(destinationPath);

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

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

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

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

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

                        _zipHelper.CreateZipFiles(sourceFile, destinationfile, true);


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

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

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

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

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

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

                        _logger.Info("Zip File Created");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Some Error occurred for Account Id " + account.Id + " Account Tag " + account.Tag);
                        _logger.Error("Message " + ex.Message);
                        _logger.Error("Stack Trace " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Some Error occurred ");
                _logger.Error("Message " + ex.Message);
                _logger.Error("Stack Trace " + ex.StackTrace);
            }
        }
        private void GenerateReportForShortName(IEnumerable <CorporateAccount> accounts)
        {
            var distinctAcesClientShortName = accounts.Where(x => !string.IsNullOrWhiteSpace(x.AcesClientShortName)).Select(t => t.AcesClientShortName)
                                              .Distinct();

            foreach (var acesClientShortName in distinctAcesClientShortName)
            {
                var accountShortNamewise = accounts.Where(a => a.AcesClientShortName == acesClientShortName);

                if (!accountShortNamewise.IsNullOrEmpty())
                {
                    var destinationFoler = _folderPath; //Path.Combine(_folderPath, clientId);
                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationFoler);
                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(_folderArchivedPath);
                    var fileNameWithoutExtention = acesClientShortName + "_Universal_Member";
                    var fileName        = fileNameWithoutExtention + ".txt";
                    var destinationFile = Path.Combine(destinationFoler, fileName);

                    if (DirectoryOperationsHelper.IsFileExist(destinationFile))
                    {
                        var archiveFileName = fileNameWithoutExtention + "_" + DateTime.Today.AddDays(-1).ToString("ddMMyyyy") + ".txt";
                        var archiveFilePath = Path.Combine(_folderArchivedPath, archiveFileName);
                        DirectoryOperationsHelper.DeleteFileIfExist(archiveFilePath);
                        DirectoryOperationsHelper.Move(destinationFile, archiveFilePath);
                    }

                    var suppressedRecordsFile = Path.Combine(destinationFoler, acesClientShortName + "_Suppressed_Member_Records.txt");

                    if (DirectoryOperationsHelper.IsFileExist(suppressedRecordsFile))
                    {
                        var archivesuppressedRecordsFileName = acesClientShortName + "_Suppressed_Member_Records_" + DateTime.Today.AddDays(-1).ToString("ddMMyyyy") + ".txt";
                        var archiveFilePath = Path.Combine(_folderArchivedPath, archivesuppressedRecordsFileName);

                        DirectoryOperationsHelper.Move(suppressedRecordsFile, Path.Combine(_folderArchivedPath, archivesuppressedRecordsFileName));
                    }

                    WriteCsvHeader(destinationFile);

                    _logger.Info("starting for account AcesClientShortName " + acesClientShortName);

                    foreach (var corporateAccount in accountShortNamewise)
                    {
                        try
                        {
                            _logger.Info("starting for account Tag " + corporateAccount.Tag);

                            var filter = new UniversalMemberListModelFilter
                            {
                                AccountId = corporateAccount.Id,
                                Tag       = corporateAccount.Tag
                            };

                            var pageNumber = 1;

                            while (true)
                            {
                                int totalRecords = 0;
                                var customers    = _customerRepository.GetCustomerForUniversalMemberReport(filter, pageNumber,
                                                                                                           PageSize, out totalRecords);

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

                                var customerIds = customers.Select(x => x.CustomerId);

                                var pcpCollection =
                                    _primaryCarePhysicianRepository.GetCustomerPcpWithoutAddress(
                                        customers.Select(x => x.CustomerId));
                                var customerEligilityCollection =
                                    _customerEligibilityRepository.GetCustomerEligibilityByCustomerIds(customerIds);
                                var languages = _languageRepository.GetAll();

                                var collection = new List <UniversalMemberViewModel>();
                                var suppressedRecordsCollection = new List <UniversalMemberViewModel>();

                                foreach (var customer in customers)
                                {
                                    var customerPcps =
                                        pcpCollection.Where(pcp => pcp.CustomerId == customer.CustomerId).ToArray();
                                    var customerEligibilityStatus =
                                        customerEligilityCollection.Where(x => x.CustomerId == customer.CustomerId).ToArray();

                                    var pcpStartDate = (DateTime?)null;
                                    var pcpEndDate   = (DateTime?)null;
                                    var pcpId        = (long?)null;
                                    if (!customerPcps.IsNullOrEmpty())
                                    {
                                        var activePcp = customerPcps.SingleOrDefault(x => x.IsActive);

                                        if (activePcp != null)
                                        {
                                            pcpStartDate = activePcp.DataRecorderMetaData.DateCreated;
                                            pcpId        = activePcp.Id;
                                        }
                                    }

                                    var eligibilityStartDate = (DateTime?)null;
                                    var eligibilityEndDate   = (DateTime?)null;

                                    if (!customerEligibilityStatus.IsNullOrEmpty())
                                    {
                                        var customerEligibilityforCurrentYear =
                                            customerEligibilityStatus.FirstOrDefault(x => x.IsEligible.HasValue && x.IsEligible.Value && x.ForYear == DateTime.Today.Year);

                                        if (customerEligibilityforCurrentYear != null)
                                        {
                                            var year = customerEligibilityforCurrentYear.ForYear;
                                            eligibilityStartDate = new DateTime(year, 1, 1);
                                            eligibilityEndDate   = new DateTime(year, 12, 31);
                                        }
                                    }

                                    var language = languages.SingleOrDefault(x => x.Id == customer.LanguageId);

                                    var model = SetUniversalMemberViewModelData(customer, corporateAccount, language, pcpStartDate, pcpEndDate, eligibilityStartDate, eligibilityEndDate, pcpId);

                                    if (string.IsNullOrWhiteSpace(model.FirstName) || string.IsNullOrWhiteSpace(model.LastName) || model.DoB == null || string.IsNullOrWhiteSpace(model.ClientMemberId))
                                    {
                                        suppressedRecordsCollection.Add(model);
                                    }
                                    else
                                    {
                                        collection.Add(model);
                                    }
                                }

                                WriteCsv(collection, destinationFile);
                                if (!suppressedRecordsCollection.IsNullOrEmpty())
                                {
                                    WriteCsvHeader(suppressedRecordsFile);

                                    WriteCsv(suppressedRecordsCollection, suppressedRecordsFile);
                                }

                                _logger.Info((pageNumber * PageSize) + " out of " + totalRecords);

                                if ((pageNumber * PageSize) >= totalRecords)
                                {
                                    break;
                                }

                                pageNumber++;
                            }

                            _logger.Info("completed for Account " + corporateAccount.Tag);
                        }
                        catch (Exception exception)
                        {
                            _logger.Error("some error occurred while created Member List for Account " + corporateAccount.Tag);
                            _logger.Error("Message: " + exception.Message);
                            _logger.Error("Stack Trace: " + exception.StackTrace);
                        }
                    }

                    if (DirectoryOperationsHelper.IsFileExist(destinationFile))
                    {
                        _logger.Info("Universal Member Report generated : " + destinationFile);

                        DirectoryOperationsHelper.CreateDirectoryIfNotExist(_sftpFolderPath);

                        _logger.Info("Deleting old file from SFTP.");
                        DirectoryOperationsHelper.DeleteFileIfExist(Path.Combine(_sftpFolderPath, acesClientShortName + "_Universal_Member.txt"));
                        _logger.Info("Old file deleted from SFTP.");

                        _logger.Info("Copying file to SFTP location : " + _sftpFolderPath);
                        var sftpFilePath = Path.Combine(_sftpFolderPath, fileName);
                        DirectoryOperationsHelper.Copy(destinationFile, sftpFilePath);
                        _logger.Info("File copied : " + sftpFilePath);
                    }
                }
            }
        }
        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 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);
            }
        }
Beispiel #16
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);
            }
        }
Beispiel #17
0
        public void PollForAppointmentEncounterData()
        {
            try
            {
                if (_settings.AppointmentEncounterReportAccountIds.IsNullOrEmpty())
                {
                    _logger.Info("No Account found for AppointmentHeader");
                    return;
                }

                var corporateAccounts = _corporateAccountRepository.GetByIds(_settings.AppointmentEncounterReportAccountIds);
                if (corporateAccounts.IsNullOrEmpty())
                {
                    _logger.Info("No Account found for AppointmentHeader");
                    return;
                }

                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info("running Report for account tag " + account.Tag);

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

                        var filter = new AppointmentEncounterFilter
                        {
                            AccountId     = account.Id,
                            EventFromDate = fromDate,
                            EventToDate   = toDate,
                            Tag           = account.Tag
                        };

                        var dataGen = new ExportableDataGenerator <AppointmentEncounterModel, AppointmentEncounterFilter>(_appointmentEncounterService.GetAppointmentEncounterReport, _logger);
                        var model   = dataGen.GetData(filter);

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

                            _logger.Info("Record count" + model.Collection.Count());
                            var folderLocation = string.Format(_settings.AppointmentEncounterReportPath, account.FolderName);

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

                            DirectoryOperationsHelper.CreateDirectoryIfNotExist(folderLocation);
                            var fileName = string.Format("EncounterHeader_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));

                            var completePath = Path.Combine(folderLocation, fileName);
                            DirectoryOperationsHelper.DeleteFileIfExist(completePath);

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

                            _logger.Info("completed Report for account tag " + account.Tag);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("some Error occurred While Appointment Encounter for Account Tag: " + account.Tag);
                        _logger.Error("Message: " + ex.Message);
                        _logger.Error("Stack Trace: " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("some Error occurred While Appointment Encounter: ");
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.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));
            }
        }
        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));
            }
        }
Beispiel #20
0
        public void PollForEventScheduleReort()
        {
            try
            {
                _logger.Info("starting Event Schedule Report");

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

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

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

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

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

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

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

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

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

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

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

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

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

                                DirectoryOperationsHelper.DeleteFileIfExist(reportfilePath);

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

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

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

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

                                    _logger.Info("File sent on sftp.");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("some Error occurred while generating report of Event Schedule Report for Account " + account.Tag + " state " + state.Name);
                            _logger.Error("ex: " + ex.Message);
                            _logger.Error("stack Trace: " + ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("some Error occurred while generating report of Event Schedule Report ");
                _logger.Error("ex: " + ex.Message);
                _logger.Error("stack Trace: " + ex.StackTrace);
            }
        }
        public void PollGiftCertificateOptumReport()
        {
            try
            {
                var corporateAccounts = _corporateAccountRepository.GetByIds(_settings.GiftCerificateOptumAccountIds);

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

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

                _logger.Info("starting for PollGiftCerificateOptumReport ");

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

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

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

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

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

                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationFoler);

                    var lastReportRunDate = toDate.AddDays(-7);

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

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

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

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

                        GenerateReport(destinationFoler, fileName, filter);

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

                        fileName = "GiftCardReport_" + toDate.ToString("yyyyMMdd") + ".csv";
                        GenerateReport(destinationFoler, fileName, filter);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.StackTrace);
            }
        }
Beispiel #22
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 GetCustomerConsentDataReport()
        {
            try
            {
                var accounts = _corporateAccountRepository.GetAllCorporateAccountToSendConsentData();
                if (accounts.IsNullOrEmpty())
                {
                    _logger.Info("No Account marked to Send Consent Data to Matrix");
                    return;
                }

                foreach (var corporateAccount in accounts)
                {
                    try
                    {
                        _logger.Info("starting for Account " + corporateAccount.Tag);

                        var serviceReportSettings = string.Format(_settings.CustomerConsentDataReportSettingPath, corporateAccount.Tag);
                        var customSettings        = _customSettingManager.Deserialize(serviceReportSettings);

                        var fromDate = customSettings.LastTransactionDate;

                        customSettings.LastTransactionDate = DateTime.Now;
                        _customSettingManager.SerializeandSave(serviceReportSettings, customSettings);

                        var filter = new CustomerConsentDataListModelFilter
                        {
                            AccountId = corporateAccount.Id,
                            Tag       = corporateAccount.Tag,
                            FromDate  = fromDate
                        };
                        var pageNumber       = 1;
                        var destinationFoler = Path.Combine(_settings.CustomerConsentDataFilePath, corporateAccount.Tag);

                        DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationFoler);

                        var fileName        = "CustomerConsentDataReport_" + DateTime.Today.ToString("yyyyMMdd") + ".txt";
                        var destinationFile = Path.Combine(destinationFoler, fileName);

                        DirectoryOperationsHelper.DeleteFileIfExist(destinationFile);

                        WriteHeader(destinationFile);

                        var index = 1;
                        while (true)
                        {
                            int totalRecords = 0;
                            var customers    = _customerRepository.GetCustomerConsentDataReport(filter, pageNumber, PageSize, out totalRecords);

                            if (customers != null)
                            {
                                foreach (var customer in customers)
                                {
                                    _logger.Info("CustomerId:" + customer.CustomerId);

                                    _logger.Info(index + " out of " + totalRecords);
                                    index++;

                                    var model = new CustomerConsentDataViewModel();
                                    model.AcesId = customer.AcesId;

                                    if (!string.IsNullOrEmpty(customer.HomePhoneNumber.ToString()) && (fromDate == null || (customer.PhoneHomeConsentUpdateDate.HasValue && customer.PhoneHomeConsentUpdateDate.Value >= fromDate)))
                                    {
                                        model.TelephoneNumber = customer.HomePhoneNumber.FormatPhoneNumber;
                                        model.ConsentType     = ((PatientConsent)customer.PhoneHomeConsentId).GetDescription();
                                        model.ConsentDateTime = customer.PhoneHomeConsentUpdateDate;
                                        WriteData(model, destinationFile);
                                    }

                                    if (!string.IsNullOrEmpty(customer.MobilePhoneNumber.ToString()) && (fromDate == null || (customer.PhoneCellConsentUpdateDate.HasValue && customer.PhoneCellConsentUpdateDate.Value >= fromDate)))
                                    {
                                        model.TelephoneNumber = customer.MobilePhoneNumber.FormatPhoneNumber;
                                        model.ConsentType     = ((PatientConsent)customer.PhoneCellConsentId).GetDescription();
                                        model.ConsentDateTime = customer.PhoneCellConsentUpdateDate;
                                        WriteData(model, destinationFile);
                                    }

                                    if (!string.IsNullOrEmpty(customer.OfficePhoneNumber.ToString()) && (fromDate == null || (customer.PhoneOfficeConsentUpdateDate.HasValue && customer.PhoneOfficeConsentUpdateDate.Value >= fromDate)))
                                    {
                                        model.TelephoneNumber = customer.OfficePhoneNumber.FormatPhoneNumber;
                                        model.ConsentType     = ((PatientConsent)customer.PhoneOfficeConsentId).GetDescription();
                                        model.ConsentDateTime = customer.PhoneOfficeConsentUpdateDate;
                                        WriteData(model, destinationFile);
                                    }
                                }
                            }

                            if ((pageNumber * PageSize) >= totalRecords)
                            {
                                break;
                            }

                            pageNumber++;
                        }

                        if (_settings.CustomerConsentDataReportSendToSftp)
                        {
                            if (ExportReportOnMatrixSftp(fileName, destinationFile))
                            {
                                _logger.Info("File posted on client SFTP");
                            }
                            else
                            {
                                _logger.Info("File didn't posted,some error occurred.");
                            }
                        }

                        _logger.Info("completed for Account " + corporateAccount.Tag);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("some error occurred while creating customer consent data report for Account " + corporateAccount.Tag);
                        _logger.Error("Message: " + ex.Message);
                        _logger.Error("Stack Trace: " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.StackTrace);
            }
        }
        public void PollForEventList()
        {
            var timeOfDay = DateTime.Now;

            _logger.Info("Time of day : " + timeOfDay.ToString("HH:mm:ss"));

            var startTime = new TimeSpan(_settings.GmsEventStartTime, 0, 0);
            var endTime   = new TimeSpan(_settings.GmsEventEndTime, 0, 0);

            if (timeOfDay.TimeOfDay < startTime || timeOfDay.TimeOfDay > endTime)
            {
                _logger.Info(string.Format("Report is generated only between {0} and {1}.", startTime.ToString(), endTime.ToString()));
                return;
            }

            _logger.Info(string.Format("Generating Event List for GMS."));
            try
            {
                var filter = new EventListGmsModelFilter
                {
                    FromDate      = DateTime.Today,
                    HealthPlanIds = _settings.GmsAccountIds
                };

                var dataGen = new ExportableDataGenerator <EventListGmsModel, EventListGmsModelFilter>(_eventReportingService.GetEventListForGmsReport, _logger);
                var model   = dataGen.GetData(filter);

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

                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(_settings.EventListGmsReportPath);

                    var reportfilePath = Path.Combine(_settings.EventListGmsReportPath, string.Format("EventList_{0}.csv", DateTime.Now.ToString("yyyyMMdd_HH")));
                    _logger.Info("File path : " + reportfilePath);

                    DirectoryOperationsHelper.DeleteFileIfExist(reportfilePath);

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

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

                        processFtp.UploadSingleFile(reportfilePath, sftpFolderReportDirectory, "");
                        _logger.Info("Sent Event List to GMS sftp.");
                    }
                    else
                    {
                        _logger.Info("Setting to send Event list to sftp is OFF.");
                    }

                    _logger.Info(string.Format("Event List generation for GMS completed."));
                }
                else
                {
                    _logger.Info("No future events found.");
                }
            }
            catch (Exception exception)
            {
                _logger.Error("Some error occurred ");
                _logger.Error("Message:  " + exception.Message);
                _logger.Error("Stack Trace:  " + exception.StackTrace);
            }
        }
Beispiel #25
0
        public void PollForBiomassEvents()
        {
            try
            {
                if (_stopTrailService)
                {
                    _logger.Info("Trail service has been stopped");
                    return;
                }
                var timeOfDay = DateTime.Now;
                if (_isDevEnvironment || timeOfDay.TimeOfDay > new TimeSpan(3, 0, 0))
                {
                    _logger.Info("Initialising xml generation.....");
                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(_bioCheckAssessmentFailedListPath);
                    var files = DirectoryOperationsHelper.GetFiles(_bioCheckAssessmentFailedListPath, "failedCustomerRecord*.xml");
                    if (files.IsNullOrEmpty())
                    {
                        _logger.Info("No Failed Customer XML found");
                        return;
                    }

                    foreach (var file in files)
                    {
                        try
                        {
                            var failedCustomerRecords = _bioCheckAssessmentFailedListXmlSerializer.Deserialize(file);

                            if (failedCustomerRecords == null || failedCustomerRecords.EventCustomers.IsNullOrEmpty())
                            {
                                _logger.Info("no record found in failedRecord XML in File: " + file);
                                continue;
                            }

                            var customerIds = failedCustomerRecords.EventCustomers.Select(x => x.CustomerId);
                            var eventid     = failedCustomerRecords.EventCustomers.First().EventId;
                            var eventData   = _eventRepository.GetById(eventid);

                            DirectoryOperationsHelper.DeleteFileIfExist(file);

                            int totalrecords;
                            var logger         = _logManager.GetLogger("FailedBioCheckJson" + eventData.Id);
                            var eventCustomers = _eventCustomerRepository.GetMyBioCheckEventCustomers(1, 400, new MyBioCheckCustomerModelFilter {
                                EventId = eventData.Id
                            }, out totalrecords);

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

                            eventCustomers = eventCustomers.Where(x => customerIds.Contains(x.CustomerId));
                            _myBioCheckAssessmentJsonHelper.GenerateJsonforEventCustomers(eventData, eventCustomers, logger);
                        }
                        catch (Exception ex)
                        {
                            _logger.Info("Some Error Occurred While generating Failed Customer BioCheck Assessment Message: " + ex.Message + " Stack Trace: " + ex.StackTrace);
                        }
                    }
                }
                else
                {
                    _logger.Info(string.Format("Generate MyBioCheck Polling can not be called as time of day is {0}", timeOfDay.TimeOfDay));
                }
            }
            catch (Exception exception)
            {
                _logger.Error(string.Format("Some Error Occurred. Message: {0} , StackTrace {1}", exception.Message, exception.StackTrace));
            }
        }
Beispiel #26
0
 private void CreateDistinationDirectory(string directoryPath)
 {
     DirectoryOperationsHelper.CreateDirectoryIfNotExist(directoryPath);
     //if (!DirectoryOperationsHelper.CreateDirectoryIfNotExist(directoryPath)) Directory.CreateDirectory(directoryPath);
 }
Beispiel #27
0
        public void Parse()
        {
            try
            {
                _logger.Info("Running Loinc Lab Data");

                if (!DirectoryOperationsHelper.CreateDirectoryIfNotExist(_settings.LoincLabDataPath))
                {
                    _logger.Info(string.Format("Folder could not be created. Please check path: {0} ", _settings.LoincLabDataPath));
                    return;
                }

                var loincMediaLocation = _mediaRepository.GetLoincMediaLocation();
                var archiveLocation    = _mediaRepository.GetLoincArchiveMediaLocation();

                var loincLabfiles = DirectoryOperationsHelper.GetFiles(_settings.LoincLabDataPath, "*.csv");
                if (loincLabfiles.IsNullOrEmpty())
                {
                    _logger.Info(string.Format("No csv file found at following location {0}", _settings.LoincLabDataPath));
                }
                else
                {
                    UploadLoincFiles(loincLabfiles, loincMediaLocation.PhysicalPath, (long)OutboundUploadType.LoincLabData);
                }

                var uploadedFiles = _outboundUploadRepository.GetAllUploadedFilesByType((long)OutboundUploadType.LoincLabData);
                if (uploadedFiles.IsNullOrEmpty())
                {
                    _logger.Info("No new files uploaded for Loinc Lab Data.");
                    return;
                }

                foreach (var uploadedFile in uploadedFiles)
                {
                    try
                    {
                        var file = GetFile(uploadedFile.FileId);

                        if (!System.IO.File.Exists(loincMediaLocation.PhysicalPath + file.Path))
                        {
                            _logger.Info("File not found : " + loincMediaLocation.PhysicalPath + file.Path);
                            continue;
                        }

                        uploadedFile.StatusId       = (long)OutboundUploadStatus.Parsing;
                        uploadedFile.ParseStartTime = DateTime.Now;
                        _outboundUploadRepository.Save(uploadedFile);

                        _logger.Info("Importing File : " + file.Path);

                        var loincLabData = _csvReader.ReadWithTextQualifierLargeData(loincMediaLocation.PhysicalPath + file.Path);

                        var csvStringBuilder = new StringBuilder();
                        csvStringBuilder.Append(LogHeader + Environment.NewLine);

                        long totalRows = 0, successRows = 0;

                        foreach (var dataTable in loincLabData)
                        {
                            if (dataTable.Rows.Count == 0)
                            {
                                _logger.Info("No records found for file : " + loincMediaLocation.PhysicalPath + file.Path);
                                continue;
                            }
                            foreach (DataRow row in dataTable.Rows)
                            {
                                totalRows++;
                                LoincLabDataEditModel model = null;

                                model = GetLoincLabData(row);

                                var errorRow = model.MemberId + "," + model.Gmpi + "," + model.Loinc + "," + model.LoincDescription + "," + model.ResultValue + "," + model.ResultUnits + "," + model.RefRange + "," + model.DoS;

                                try
                                {
                                    if (model != null && !model.IsEmpty())
                                    {
                                        var domain = new LoincLabData
                                        {
                                            MemberId         = model.MemberId,
                                            Gmpi             = model.Gmpi,
                                            Loinc            = model.Loinc,
                                            LoincDescription = model.LoincDescription,
                                            ResultValue      = model.ResultValue,
                                            ResultUnits      = model.ResultUnits,
                                            RefRange         = model.RefRange,
                                            DateOfService    = GetRowDateValue(model.DoS),
                                            Year             = DateTime.Today.Year,
                                            DateCreated      = DateTime.Now,
                                            UploadId         = uploadedFile.Id,
                                        };

                                        _loincLabDataRepository.Save(domain);
                                    }

                                    successRows++;
                                }
                                catch (Exception ex)
                                {
                                    _logger.Error(string.Format("Some Error Occurred Message: {0} \n stack Trace: {1}", ex.Message, ex.StackTrace));
                                    csvStringBuilder.Append(errorRow + "," + ex.Message + Environment.NewLine);
                                }
                            }
                        }

                        if (successRows < totalRows)
                        {
                            var logFileName = file.Path + "_Log.csv";

                            var logFile = SaveLogFile(_settings.LoincLabDataPath + logFileName, csvStringBuilder);
                            uploadedFile.LogFileId = logFile.Id;
                        }

                        uploadedFile.SuccessUploadCount = successRows;
                        uploadedFile.FailedUploadCount  = totalRows - successRows;
                        uploadedFile.ParseEndTime       = DateTime.Now;
                        uploadedFile.StatusId           = successRows > 0 ? (long)OutboundUploadStatus.Parsed : (long)OutboundUploadStatus.ParseFailed;
                        _outboundUploadRepository.Save(uploadedFile);

                        if (successRows > 1)
                        {
                            System.IO.File.Move(loincMediaLocation.PhysicalPath + file.Path, archiveLocation.PhysicalPath + file.Path);
                            ((IFileRepository)_fileRepository).MarkasArchived(file.Id);
                        }
                    }
                    catch (Exception ex)
                    {
                        uploadedFile.StatusId = (long)OutboundUploadStatus.ParseFailed;
                        _outboundUploadRepository.Save(uploadedFile);
                        _logger.Error(string.Format("while Parsing File"));
                        _logger.Error("Ex Message" + ex.Message);
                        _logger.Error("Ex Stack Trace " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error while Parsing Loinc Lab Data Files.");
                _logger.Error(ex);
            }
        }
        public void PollForReport()
        {
            if (_healthPlanIds.IsNullOrEmpty())
            {
                _logger.Info("No Health Plan IDs found.");
                return;
            }

            var healthPlans = _corporateAccountRepository.GetByIds(_healthPlanIds);

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

            var collection = new List <GmsExcludedCustomerViewModel>();

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

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

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

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

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

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

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

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

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

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

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

            var excludedPath = _settings.GmsExcludeReportDownloadCustomerPath;

            if (DirectoryOperationsHelper.CreateDirectoryIfNotExist(excludedPath))
            {
                var fileName = Path.Combine(excludedPath, string.Format("ExcludedPatientList_{0}.csv", DateTime.Today.ToString("yyyyMMdd")));
                WriteCsv(collection, fileName);
            }
            else
            {
                _logger.Error("Folder can not be created");
            }
        }
        private void GenerateReport(EventScheduleListModelFilter eventScheduleModelFilter, PotentialPcpChangeReportModelFilter filter, CorporateAccount account)
        {
            var stateIds = (IReadOnlyCollection <long>)_eventRepository.GetEventStateByAccountId(eventScheduleModelFilter);

            if (stateIds.IsNullOrEmpty())
            {
                _logger.Info("No State found for Wellmed");             //Do not return from here as we are updating last transaction date at last
            }

            var states = _stateRepository.GetStates(stateIds);

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

                    var dataGen = new ExportableDataGenerator <PotentialPcpChangeReportViewModel, PotentialPcpChangeReportModelFilter>(_potentialPcpChangeReportService.GetPotentialPcpChangeData, _logger);
                    filter.StateId = state.Id;
                    var model = dataGen.GetData(filter);

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

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

                        DirectoryOperationsHelper.CreateDirectoryIfNotExist(reportfilePath);
                        reportfilePath = Path.Combine(reportfilePath, string.Format("WellMed_PCP_Change_Report_{0}.csv", filter.StartDate.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 Potential Pcp Change report on sftp for StateId: " + state.Id + " State: " + state.Name);

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

                            _logger.Info("Potential Pcp Change report posted on sftp for StateId: " + state.Id + " State: " + state.Name);
                        }
                        _logger.Info("Potential Pcp Change Report generation completed for StateId: " + state.Id + " State: " + state.Name);
                    }
                    else
                    {
                        _logger.Info("No data 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);
                }
            }

            //update custom setting XML
            var customSetting = _customSettingManager.Deserialize(_pcpCustomSetting);

            customSetting.LastTransactionDate = filter.EndDate;
            _customSettingManager.SerializeandSave(_pcpCustomSetting, customSetting);
        }
Beispiel #30
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;
            }
        }