Esempio n. 1
0
        public static void SetServiceCodeForNotification(NtbsContext context, int notificationId, string code)
        {
            var notification = context.Notification.Find(notificationId);

            notification.HospitalDetails.TBServiceCode = code;
            context.SaveChanges();
        }
Esempio n. 2
0
        public static void SetPostcodeForNotification(NtbsContext context, int notificationId, string code)
        {
            var notification = context.Notification.Find(notificationId);

            notification.PatientDetails.PostcodeToLookup = code;
            context.SaveChanges();
        }
Esempio n. 3
0
        public static void SeedDatabase(NtbsContext context)
        {
            // General purpose entities shared between tests
            context.Notification.AddRange(GetSeedingNotifications());

            context.SaveChanges();
        }
Esempio n. 4
0
        public static void SeedDatabase(NtbsContext context)
        {
            // General purpose entities shared between tests
            context.Notification.AddRange(GetSeedingNotifications());
            context.PostcodeLookup.AddRange(GetTestPostcodeLookups());
            context.NotificationGroup.AddRange(GetTestNotificationGroups());
            context.User.AddRange(GetCaseManagers());
            context.CaseManagerTbService.AddRange(GetCaseManagerTbServicesJoinEntries());
            context.Alert.AddRange(GetSeedingAlerts());

            // Entities required for specific test suites
            context.Notification.AddRange(OverviewPageTests.GetSeedingNotifications());
            context.Notification.AddRange(DenotifyPageTests.GetSeedingNotifications());
            context.Notification.AddRange(DeletePageTests.GetSeedingNotifications());
            context.Notification.AddRange(PatientPageTests.GetSeedingNotifications());
            context.Notification.AddRange(HospitalDetailsPageTests.GetSeedingNotifications());
            context.Notification.AddRange(ManualTestResultEditPagesTests.GetSeedingNotifications());
            context.Notification.AddRange(SocialContextVenueEditPageTests.GetSeedingNotifications());
            context.Notification.AddRange(SocialContextAddressEditPageTests.GetSeedingNotifications());
            context.Notification.AddRange(TreatmentEventEditPageTests.GetSeedingNotifications());
            context.Notification.AddRange(ClinicalDetailsPageTests.GetSeedingNotifications());
            context.Notification.AddRange(ActionTransferPageTests.GetSeedingNotifications());
            context.Notification.AddRange(LabResultsPageTests.GetSeedingNotifications());
            context.Notification.AddRange(MBovisExposureToKnownCasesPageTests.GetSeedingNotifications());
            context.Notification.AddRange(MBovisUnpasteurisedMilkConsumptionPageTests.GetSeedingNotifications());
            context.Notification.AddRange(MBovisOccupationExposurePageTests.GetSeedingNotifications());
            context.Notification.AddRange(MBovisAnimalExposurePageTests.GetSeedingNotifications());
            context.Notification.AddRange(DraftEditPageTests.GetSeedingNotifications());

            context.TreatmentOutcome.AddRange(TreatmentEventEditPageTests.GetSeedingOutcomes());

            context.Alert.AddRange(DraftEditPageTests.GetSeedingAlerts());

            context.SaveChanges();
        }
Esempio n. 5
0
        public UserRepositoryTests(RepositoryFixture <UserRepository> userRepositoryFixture)
        {
            ContextHelper.DisableAudits();
            _context        = userRepositoryFixture.Context;
            _contextOptions = userRepositoryFixture.ContextOptions;

            var optionsMonitor = new Mock <IOptionsMonitor <AdOptions> >();

            optionsMonitor.Setup(om => om.CurrentValue).Returns(new AdOptions {
                ReadOnlyUserGroup = "ReadOnly"
            });
            _userRepo = new UserRepository(_context, optionsMonitor.Object);

            var phec = new PHEC {
                Code = "E45000001", Name = "London"
            };

            _tbService1 = new TBService {
                Code = "TBS0001", IsLegacy = false, PHECCode = "E45000001"
            };
            _tbService2 = new TBService {
                Code = "TBS0002", IsLegacy = false, PHECCode = "E45000001"
            };
            _context.PHEC.Add(phec);
            _context.TbService.AddRange(_tbService1, _tbService2);
            _context.SaveChanges();
        }
Esempio n. 6
0
        private static async Task <int> GetExpectedUserResults(NtbsContext context, string searchKeyword)
        {
            // This method is a replication of the UserSearchService which bypasses all calls to the
            // referenceDataRepository service

            var allPhecs = await context.PHEC.OrderBy(x => x.Name).ToListAsync();

            var caseManagersAndRegionalUsers = (await context.User
                                                .Include(u => u.CaseManagerTbServices)
                                                .OrderBy(u => u.DisplayName)
                                                .ToListAsync())
                                               .Where(u => u.IsActive && (u.CaseManagerTbServices.Any() ||
                                                                          (u.AdGroups != null &&
                                                                           allPhecs.Any(phec => u.AdGroups.Split(",").Contains(phec.AdGroup)))));

            var filteredCaseManagersAndRegionalUsers = caseManagersAndRegionalUsers
                                                       .Where(c =>
                                                              c.FamilyName != null &&
                                                              c.FamilyName.ToLower().Contains(searchKeyword) ||
                                                              c.GivenName != null && c.GivenName.ToLower().Contains(searchKeyword) ||
                                                              c.DisplayName != null && c.DisplayName.ToLower().Contains(searchKeyword))
                                                       .ToList();

            return(filteredCaseManagersAndRegionalUsers.Count);
        }
Esempio n. 7
0
 public NotificationClusterUpdateJob(
     INotificationClusterRepository notificationClusterRepository,
     INotificationService notificationService,
     NtbsContext ntbsContext) : base(ntbsContext)
 {
     _notificationClusterRepository = notificationClusterRepository;
     _notificationService           = notificationService;
 }
 private NtbsContext SetupTestDatabase(NtbsContext context)
 {
     context.Notification.AddRange(new List <Notification>
     {
         new Notification
         {
             NotificationId   = 1,
             ETSID            = "12",
             LTBRID           = "222",
             LTBRPatientId    = "22",
             NotificationDate = new DateTime(2000, 1, 1),
             PatientDetails   =
                 new PatientDetails
             {
                 FamilyName       = "Merry",
                 GivenName        = "Christmas",
                 NhsNumber        = "1234567890",
                 SexId            = 1,
                 CountryId        = 1,
                 Dob              = new DateTime(1990, 1, 1),
                 PostcodeToLookup = "SW12RT"
             },
             HospitalDetails = new HospitalDetails {
                 TBServiceCode = "Ashford hospital"
             },
             DrugResistanceProfile = new DrugResistanceProfile {
                 Species = string.Empty, DrugResistanceProfileString = string.Empty
             }
         },
         new Notification
         {
             NotificationId   = 2,
             ETSID            = "13",
             LTBRID           = "223",
             LTBRPatientId    = "23",
             NotificationDate = new DateTime(2001, 1, 1),
             PatientDetails   =
                 new PatientDetails
             {
                 FamilyName       = "Merry",
                 GivenName        = "Goround",
                 NhsNumber        = "1234567891",
                 SexId            = 2,
                 CountryId        = 2,
                 Dob              = new DateTime(1991, 1, 1),
                 PostcodeToLookup = "SW294FB"
             },
             HospitalDetails = new HospitalDetails {
                 TBServiceCode = "Not Ashford"
             },
             DrugResistanceProfile = new DrugResistanceProfile {
                 Species = string.Empty, DrugResistanceProfileString = string.Empty
             }
         }
     });
     context.SaveChanges();
     return(context);
 }
 public DataQualityAlertsJob(
     IAlertService alertService,
     IDataQualityRepository dataQualityRepository,
     NtbsContext ntbsContext) : base(ntbsContext)
 {
     _alertService          = alertService;
     _dataQualityRepository = dataQualityRepository;
     _context = ntbsContext;
 }
Esempio n. 10
0
 public UnmatchedLabResultAlertsJob(
     ISpecimenService specimenService,
     IAlertRepository alertRepository,
     IAlertService alertService,
     NtbsContext ntbsContext) : base(ntbsContext)
 {
     _specimenService = specimenService;
     _alertRepository = alertRepository;
     _alertService    = alertService;
 }
        private int GetUserIdFromUsername(string username)
        {
            var options = new DbContextOptionsBuilder <NtbsContext>();

            options.UseSqlServer(Settings.EnvironmentConfig.ConnectionString);
            using (var context = new NtbsContext(options.Options))
            {
                return(context.User.Single(u => u.Username.ToLower() == username.ToLower()).Id);
            }
        }
Esempio n. 12
0
 private User GetUserUsingNewContext(string username)
 {
     using (var newContext = new NtbsContext(_contextOptions))
     {
         var updatedUser = newContext.User
                           .Include(u => u.CaseManagerTbServices)
                           .ThenInclude(cmtbs => cmtbs.TbService)
                           .FirstOrDefault(u => u.Username == username);
         return(updatedUser);
     }
 }
        public async Task InitializeAsync()
        {
            var contextOptions = new DbContextOptionsBuilder <NtbsContext>()
                                 .UseInMemoryDatabase(nameof(HomePageTests))
                                 .Options;

            Context = new NtbsContext(contextOptions);
            await Context.Database.EnsureDeletedAsync();

            await Context.Database.EnsureCreatedAsync();
        }
        public async Task InitializeAsync()
        {
            ContextOptions = new DbContextOptionsBuilder <NtbsContext>()
                             .UseSqlite($"Filename={typeof(T)}.db")
                             .Options;

            Context = new NtbsContext(ContextOptions);
            await Context.Database.EnsureDeletedAsync();

            await Context.Database.EnsureCreatedAsync();
        }
Esempio n. 15
0
        static async Task GenerateNotifications(NtbsContext context, bool addTreatmentEvents = false)
        {
            var numberOfNotifications = 3000;
            var rand      = new Random();
            var hospitals = (await context.Hospital.ToListAsync());

            var notificationsOperable = Builder <Notification> .CreateListOfSize(numberOfNotifications)
                                        .All()
                                        .With(n => n.NotificationId              = 0)
                                        .With(n => n.NotificationStatus          = NotificationStatus.Notified)
                                        .With(n => n.PatientDetails.GivenName    = Faker.Name.First())
                                        .With(n => n.PatientDetails.FamilyName   = Faker.Name.Last())
                                        .With(n => n.PatientDetails.NoFixedAbode = true)
                                        .With(n => n.TestData.HasTestCarriedOut  = false)
                                        .With(n => n.ClinicalDetails.Notes       = "UniqueBulkInsert")
                                        .With(n => n.GroupId = null)
                                        // Add randomised fields that Faker cannot generate
                                        .With(n => n.PatientDetails.Dob         = AddRandomDateTimeBetween1950And2000(rand))
                                        .With(n => n.PatientDetails.SexId       = rand.Next(1, 3))
                                        .With(n => n.PatientDetails.EthnicityId = 4)
                                        .With(n => n.PatientDetails.CountryId   = 235)
                                        .With(n => n.NotificationDate           = AddRandomDateTimeBetween2014And2017(rand))
                                        .With(n =>
            {
                var hospital = GetRandomHospital(rand, hospitals);
                n.HospitalDetails.TBServiceCode = hospital.TBServiceCode;
                n.HospitalDetails.HospitalId    = hospital.HospitalId;
                return(true);
            }
                                              )
                                        .With(n => n.HospitalDetails.HospitalId = hospitals.FirstOrDefault(h => h.TBServiceCode == n.HospitalDetails.TBServiceCode)?.HospitalId)
                                        .With(n => n.PatientDetails.NhsNumber   = AddRandomTestNhsNumber(rand))
                                        .With(n => n.NotificationSites          = new List <NotificationSite>
            {
                new NotificationSite
                {
                    SiteId = 1
                }
            })
                                        .With(n => n.ClinicalDetails.DiagnosisDate = new DateTime(2014, 1, 1))
                                        .With(n => n.DeletionReason = null);


            if (addTreatmentEvents)
            {
                notificationsOperable = await AddDataQualityTreatmentEvents(notificationsOperable, context);
            }

            var notifications = notificationsOperable.Build();

            context.AddRange(notifications);
            await context.SaveChangesAsync();
        }
        private void SaveNotificationInDatabase(Notification notification)
        {
            var options = new DbContextOptionsBuilder <NtbsContext>();

            options.UseSqlServer(Settings.EnvironmentConfig.ConnectionString);
            using (var context = new NtbsContext(options.Options))
            {
                context.Add(notification);
                context.SaveChanges();
            }
            TestContext.AddedNotificationIds.Add(notification.NotificationId);
        }
        public HospitalDetailsModel(
            INotificationService notificationService,
            INotificationRepository notificationRepository,
            IAlertRepository alertRepository,
            IReferenceDataRepository referenceDataRepository,
            IAuthorizationService authorizationService,
            IUserService userService,
            NtbsContext context) : base(notificationService, authorizationService, notificationRepository, alertRepository)
        {
            _context                 = context;
            _userService             = userService;
            _referenceDataRepository = referenceDataRepository;

            CurrentPage = NotificationSubPaths.EditHospitalDetails;
        }
        public async Task FiltersOutNotificationsWithTheAlertTypeAlreadyPresent()
        {
            // ARRANGE
            using (var context = new NtbsContext(ContextOptions))
            {
                await context.Database.EnsureDeletedAsync();

                await context.Database.EnsureCreatedAsync();

                // We will use the birth country alert as a proxy for testing the common path ways of the
                // data quality repository
                // All seeded notifications will be eligible for this alert

                var notification1 = NotificationEligibleForCountryOfBirthDqAlert(NoAlertsName);

                var notification2 = NotificationEligibleForCountryOfBirthDqAlert(BirthCountryAlertName);
                notification2.Alerts = new List <Alert> {
                    new DataQualityBirthCountryAlert()
                };

                var notification3 = NotificationEligibleForCountryOfBirthDqAlert(ClinicalDatesAlertName);
                notification3.Alerts = new List <Alert> {
                    new DataQualityClinicalDatesAlert()
                };

                await context.AddRangeAsync(notification1, notification2, notification3);

                await context.SaveChangesAsync();
            }

            using (var context = new NtbsContext(ContextOptions))
            {
                var repo = new DataQualityRepository(context);

                // ACT
                // Get all possible ones
                var notifications = await repo.GetNotificationsEligibleForDqBirthCountryAlertsAsync(100, 0);

                // ASSERT
                // Out of the 3 eligible notifications, 1 already has the alert
                Assert.True(notifications.Any(n => n.PatientDetails.FamilyName == NoAlertsName),
                            "Eligible notification with no other alerts not selected");
                Assert.True(notifications.Any(n => n.PatientDetails.FamilyName == ClinicalDatesAlertName),
                            "Eligible notification with only other alerts types not selected");
                Assert.Equal(2, notifications.Count);
            }
        }
 public NotificationService(
     INotificationRepository notificationRepository,
     IReferenceDataRepository referenceDataRepository,
     IUserService userService,
     ITreatmentEventRepository treatmentEventRepository,
     NtbsContext context,
     ISpecimenService specimenService,
     IAlertService alertService)
 {
     _notificationRepository   = notificationRepository;
     _referenceDataRepository  = referenceDataRepository;
     _userService              = userService;
     _treatmentEventRepository = treatmentEventRepository;
     _context         = context;
     _specimenService = specimenService;
     _alertService    = alertService;
 }
Esempio n. 20
0
        public static void SeedDatabase(NtbsContext context)
        {
            // Reference data
            context.PHEC.AddRange(ReferenceDataSeedingHelper.GetPHECList());
            context.TbService.AddRange(ReferenceDataSeedingHelper.GetTBServices());
            context.Hospital.AddRange(ReferenceDataSeedingHelper.GetHospitalsList());
            context.LocalAuthority.AddRange(ReferenceDataSeedingHelper.GetLocalAuthorities());
            context.LocalAuthorityToPhec.AddRange(ReferenceDataSeedingHelper.GetLAtoPHECs());
            context.PostcodeLookup.AddRange(ReferenceDataSeedingHelper.GetPostcodeLookups());

            // General purpose entities shared between tests
            context.User.AddRange(GetCaseManagers());
            context.Notification.AddRange(GetSeedingNotifications());
            context.NotificationGroup.AddRange(GetTestNotificationGroups());
            context.CaseManagerTbService.AddRange(GetCaseManagerTbServicesJoinEntries());
            context.Alert.AddRange(GetSeedingAlerts());
            context.ReleaseVersion.Add(new ReleaseVersion {
                Version = "test-version", Date = DateTime.UtcNow
            });

            // Entities required for specific test suites
            context.Notification.AddRange(OverviewPageTests.GetSeedingNotifications());
            context.Notification.AddRange(DenotifyPageTests.GetSeedingNotifications());
            context.Notification.AddRange(DeletePageTests.GetSeedingNotifications());
            context.Notification.AddRange(PatientPageTests.GetSeedingNotifications());
            context.Notification.AddRange(HospitalDetailsPageTests.GetSeedingNotifications());
            context.Notification.AddRange(TransferPageTests.GetSeedingNotifications());
            context.Notification.AddRange(ManualTestResultEditPagesTests.GetSeedingNotifications());
            context.Notification.AddRange(SocialContextVenueEditPageTests.GetSeedingNotifications());
            context.Notification.AddRange(SocialContextAddressEditPageTests.GetSeedingNotifications());
            context.Notification.AddRange(TreatmentEventEditPageTests.GetSeedingNotifications());
            context.Notification.AddRange(ClinicalDetailsPageTests.GetSeedingNotifications());
            context.Notification.AddRange(ActionTransferPageTests.GetSeedingNotifications());
            context.Notification.AddRange(LabResultsPageTests.GetSeedingNotifications());
            context.Notification.AddRange(MBovisExposureToKnownCasesPageTests.GetSeedingNotifications());
            context.Notification.AddRange(MBovisUnpasteurisedMilkConsumptionPageTests.GetSeedingNotifications());
            context.Notification.AddRange(MBovisOccupationExposurePageTests.GetSeedingNotifications());
            context.Notification.AddRange(MBovisAnimalExposurePageTests.GetSeedingNotifications());
            context.Notification.AddRange(DraftEditPageTests.GetSeedingNotifications());

            context.TreatmentOutcome.AddRange(TreatmentEventEditPageTests.GetSeedingOutcomes());

            context.Alert.AddRange(DraftEditPageTests.GetSeedingAlerts());

            context.SaveChanges();
        }
Esempio n. 21
0
 public void ThenAnAlertHasBeenCreated(string title)
 {
     WithErrorLogging(() =>
     {
         var options = new DbContextOptionsBuilder <NtbsContext>();
         options.UseSqlServer(Settings.EnvironmentConfig.ConnectionString);
         using (var context = new NtbsContext(options.Options))
         {
             var alertType = Enum.Parse <AlertType>(title);
             var matchingAlertsForNotificationInTest = context.Alert
                                                       .Where(a => a.NotificationId.HasValue &&
                                                              TestContext.AddedNotificationIds.Contains(a.NotificationId.Value) &&
                                                              a.AlertType == alertType);
             Assert.NotEmpty(matchingAlertsForNotificationInTest);
         }
     });
 }
Esempio n. 22
0
        public CaseManagerImportServiceTests()
        {
            _context = SetupTestContext();
            ContextHelper.DisableAudits();
            SetupMockMigrationRepo();
            _adOptionMock.Setup(s => s.CurrentValue).Returns(new AdOptions {
                ReadOnlyUserGroup = "TestReadOnly"
            });
            IUserRepository                      userRepository                   = new UserRepository(_context, _adOptionMock.Object);
            IReferenceDataRepository             referenceDataRepository          = new ReferenceDataRepository(_context);
            Mock <INotificationImportRepository> mockNotificationImportRepository = new Mock <INotificationImportRepository>();

            var importLogger = new ImportLogger(mockNotificationImportRepository.Object);

            _caseManagerImportService = new CaseManagerImportService(userRepository, referenceDataRepository,
                                                                     _migrationRepositoryMock.Object, importLogger);
        }
        public TreatmentEventMapperTest()
        {
            _context = SetupTestContext();
            _referenceDataRepository = new ReferenceDataRepository(_context);
            _adOptionMock.Setup(s => s.CurrentValue).Returns(new AdOptions {
                ReadOnlyUserGroup = "TestReadOnly"
            });
            var userRepo      = new UserRepository(_context, _adOptionMock.Object);
            var migrationRepo = new Mock <IMigrationRepository>();

            migrationRepo.Setup(mr => mr.GetLegacyUserByUsername(It.IsAny <string>()))
            .Returns((string username) => Task.FromResult(_usernameToLegacyUserDict[username]));
            migrationRepo.Setup(repo => repo.GetLegacyUserHospitalsByUsername(It.IsAny <string>()))
            .ReturnsAsync((string username) => new List <MigrationLegacyUserHospital>());
            var importLogger = new Mock <IImportLogger>();

            _caseManagerImportService =
                new CaseManagerImportService(userRepo, _referenceDataRepository, migrationRepo.Object, importLogger.Object);
            _treatmentEventMapper = new TreatmentEventMapper(_caseManagerImportService, _referenceDataRepository);
        }
Esempio n. 24
0
        public AdImportServiceTest()
        {
            _context = SetupTestContext();
            ContextHelper.DisableAudits();

            _adUsers = new List <LdapEntry>();
            var adDirectoryService = SetupMockAdDirectoryService();

            _adDirectoryServiceFactoryMock.Setup(s => s.Create()).Returns(adDirectoryService);
            _adOptionMock.Setup(s => s.CurrentValue).Returns(new AdOptions {
                ReadOnlyUserGroup = "TestReadOnly"
            });

            var referenceRepo = new ReferenceDataRepository(_context);
            var userRepo      = new UserRepository(_context, _adOptionMock.Object);
            var adUserService = new AdUserService(userRepo);

            _adImportService = new AdImportService(
                _adDirectoryServiceFactoryMock.Object,
                referenceRepo,
                adUserService);
        }
        public NotificationImportHelper(IOptions <MigrationConfig> migrationConfig, NtbsContext ntbsContext)
        {
            var ntbsEnvironment = migrationConfig.Value.NtbsEnvironment ?? string.Empty;

            // We only allow alphanumeric values in the environment name, as a basic guard against SQL injection.
            // (In practice it's hard to imagine a scenario where a malicious actor is able to set environment variables
            // for our app, and yet unable to mutate the database directly, however, it's prudent to put this in).
            _ntbsEnvironment = string.Concat(ntbsEnvironment.Where(char.IsLetterOrDigit));

            // The BulkInsertImportedNotificationsQueryTemplate query needs the name of the app
            // database - see its doc for more info
            try
            {
                _ntbsDb = ntbsContext.Database.GetDbConnection().Database;
            }
            catch (InvalidOperationException)
            {
                // In test, we mock out the db, so it's not possible to get the db name from the context - nor would calling
                // the methods that rely on it make sense.
                _ntbsDb = "";
            }
        }
Esempio n. 26
0
        static async Task Main(string[] args)
        {
            bool addTreatmentEvents = true;

            if (args.Length > 0)
            {
                addTreatmentEvents = args[0] != "--withDqAlerts";
            }
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.Development.json", optional: false, reloadOnChange: true);

            Directory.SetCurrentDirectory("./bin/debug/netcoreapp2.2");
            builder.SetBasePath(Directory.GetCurrentDirectory());

            var configuration = builder.Build();

            var connectionString = configuration.GetConnectionString("ntbsContext");

            var options = new DbContextOptionsBuilder <NtbsContext>()
                          .UseSqlServer(connectionString)
                          .Options;

            using (var context = new NtbsContext(options))
            {
                if (!context.Database.GetService <IRelationalDatabaseCreator>().Exists())
                {
                    Console.WriteLine("Database does not exist, aborting bulk insert");
                    return;
                }
                Console.WriteLine("Starting generation of notifications");
                await GenerateNotifications(context, addTreatmentEvents);

                Console.WriteLine("Finished generation of notifications");
            }
        }
 public CloseInactiveNotificationsJob(INotificationService notificationService, NtbsContext ntbsContext)
     : base(ntbsContext)
 {
     _notificationService = notificationService;
 }
 public DataQualityRepositoryTests(RepositoryFixture <DataQualityRepository> dataQualityRepositoryFixture)
 {
     ContextHelper.DisableAudits();
     _context = dataQualityRepositoryFixture.Context;
 }
 public NotificationCloningService(NtbsContext context)
 {
     _context = context;
 }
 public PostcodeService(NtbsContext context)
 {
     _context = context;
 }