Ejemplo n.º 1
0
        public async Task <Guid> Copy(Guid organizationID)
        {
            var existing = await(from o in DataContext.Organizations where o.ID == organizationID && o.OrganizationType == DTO.Enums.OrganizationType.Local select o).FirstOrDefaultAsync();

            if (existing == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The Organization could not be found."));
            }

            if (!await DataContext.HasPermissions <Organization>(Identity, existing.ID, PermissionIdentifiers.Organization.Copy))
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You do not have permission to copy the specified organization."));
            }

            string newAcronym = "New " + existing.Acronym;
            string newName    = "New " + existing.Name;

            while (await(from p in DataContext.Organizations where !p.Deleted && (p.Name == newName && p.Acronym == newAcronym) select p).AnyAsync())
            {
                newAcronym = "New " + newAcronym;
                newName    = "New " + newName;
            }

            var organization = new Organization
            {
                Acronym = newAcronym,
                Name    = newName,
                ParentOrganizationID          = existing.ParentOrganizationID,
                ApprovalRequired              = existing.ApprovalRequired,
                ContactEmail                  = existing.ContactEmail,
                ContactFirstName              = existing.ContactFirstName,
                ContactLastName               = existing.ContactLastName,
                ContactPhone                  = existing.ContactPhone,
                SpecialRequirements           = existing.SpecialRequirements,
                UsageRestrictions             = existing.UsageRestrictions,
                HealthPlanDescription         = existing.HealthPlanDescription,
                EnableClaimsAndBilling        = existing.EnableClaimsAndBilling,
                EnableEHRA                    = existing.EnableEHRA,
                EnableRegistries              = existing.EnableRegistries,
                DataModelESP                  = existing.DataModelESP,
                DataModelHMORNVDW             = existing.DataModelHMORNVDW,
                DataModelI2B2                 = existing.DataModelI2B2,
                DataModelMSCDM                = existing.DataModelMSCDM,
                DataModelOMOP                 = existing.DataModelOMOP,
                DataModelOther                = existing.DataModelOther,
                DataModelOtherText            = existing.DataModelOtherText,
                PragmaticClinicalTrials       = existing.PragmaticClinicalTrials,
                Biorepositories               = existing.Biorepositories,
                PatientReportedBehaviors      = existing.PatientReportedBehaviors,
                PatientReportedOutcomes       = existing.PatientReportedOutcomes,
                PrescriptionOrders            = existing.PrescriptionOrders,
                InpatientEHRApplication       = existing.InpatientEHRApplication,
                OutpatientEHRApplication      = existing.OutpatientEHRApplication,
                OtherInpatientEHRApplication  = existing.OtherInpatientEHRApplication,
                OtherOutpatientEHRApplication = existing.OtherOutpatientEHRApplication,
                InpatientClaims               = existing.InpatientClaims,
                OutpatientClaims              = existing.OutpatientClaims,
                ObservationalParticipation    = existing.ObservationalParticipation,
                ProspectiveTrials             = existing.ProspectiveTrials,
                EnrollmentClaims              = existing.EnrollmentClaims,
                DemographicsClaims            = existing.DemographicsClaims,
                LaboratoryResultsClaims       = existing.LaboratoryResultsClaims,
                VitalSignsClaims              = existing.LaboratoryResultsClaims,
                OtherClaims                   = existing.OtherClaims,
                OtherClaimsText               = existing.OtherClaimsText,
                ObservationClinicalExperience = existing.ObservationClinicalExperience,
                OrganizationType              = existing.OrganizationType
            };

            DataContext.Organizations.Add(organization);

            var orgDTO = new OrganizationDTO()
            {
                ID      = organization.ID,
                Name    = organization.Name,
                Acronym = organization.Acronym,
                ParentOrganizationID = organization.ParentOrganizationID,
                ContactEmail         = organization.ContactEmail,
                ContactFirstName     = organization.ContactFirstName,
                ContactLastName      = organization.ContactLastName,
                ContactPhone         = organization.ContactPhone
            };

            #region CNDS
            Guid networkID = await CNDSEntityUpdater.GetNetworkID(DataContext);

            if (CNDSEntityUpdater.CanUpdateCNDS)
            {
                try
                {
                    using (var cnds = new CNDSEntityUpdater(networkID))
                    {
                        var response = await CNDSEntityUpdater.GetCNDSEntityIdentifiers(new[] { organizationID });

                        var cndsOrgID = response.Select(org => org.EntityID).FirstOrDefault();

                        if (cndsOrgID == default(Guid))
                        {
                            throw new System.Net.Http.HttpRequestException("Organization not found in CNDS.");
                        }

                        var availOrgMetdata = await CNDSEntityUpdater.CNDS.Domain.List("$filter=EntityType eq Lpp.CNDS.DTO.Enums.EntityType'0'");

                        var currentOrgMetadata = await CNDSEntityUpdater.CNDS.Organizations.ListOrganizationDomains(cndsOrgID);

                        List <MetadataDTO> meta = new List <MetadataDTO>();
                        foreach (var metadata in availOrgMetdata.Where(x => x.ParentDomainID == null))
                        {
                            meta.Add(cnds.GetMetadataChildren(metadata.ID, availOrgMetdata, currentOrgMetadata, null, null));
                        }
                        orgDTO.Metadata = meta;
                        await CNDSEntityUpdater.RegisterOrUpdateOrganizations(orgDTO);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message, ex);
                }
            }

            #endregion CNDS

            //Registries
            var existingRegistries = await(from reg in DataContext.OrganizationRegistries where reg.OrganizationID == existing.ID select reg).ToArrayAsync();
            foreach (var existingRegistry in existingRegistries)
            {
                var reg = new OrganizationRegistry
                {
                    RegistryID     = existingRegistry.RegistryID,
                    OrganizationID = organization.ID,
                    Description    = existingRegistry.Description
                };
                DataContext.OrganizationRegistries.Add(reg);
            }

            //Security Groups
            var existingSecurityGroups = await(from sg in DataContext.SecurityGroups.Include(x => x.Users) where sg.OwnerID == existing.ID orderby sg.ParentSecurityGroupID select sg).ToArrayAsync();
            var SecurityGroupMap       = new Dictionary <Guid, Guid>();

            CopySecurityGroups(existingSecurityGroups, ref SecurityGroupMap, null, organization);

            await DataContext.SaveChangesAsync();

            //All of these are done this way with a conditional if because the triggers cause inserts that entity framework is not aware of. Note that they are parameterized to ensure no sql injections.

            foreach (var user in existingSecurityGroups.SelectMany(u => u.Users).DistinctBy(u => new { u.SecurityGroupID, u.UserID }))
            {
                await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM SecurityGroupUsers WHERE UserID = @UserID AND SecurityGroupID = @SecurityGroupID)
	INSERT INTO SecurityGroupUsers (UserID, SecurityGroupID, Overridden) VALUES (@UserID, @SecurityGroupID, 0)"    , new SqlParameter("UserID", user.UserID), new SqlParameter("SecurityGroupID", SecurityGroupMap[user.SecurityGroupID]));
            }



            //Org Acls
            var existingSecurityGroupIDs = SecurityGroupMap.Select(gm => gm.Key).ToArray();
            var existingOrganizationAcls = await(from a in DataContext.OrganizationAcls where a.OrganizationID == existing.ID && existingSecurityGroupIDs.Contains(a.SecurityGroupID) select a).Distinct().ToArrayAsync();

            foreach (var existingOrganizationAcl in existingOrganizationAcls)
            {
                if (!SecurityGroupMap.ContainsKey(existingOrganizationAcl.SecurityGroupID))
                {
                    SecurityGroupMap.Add(existingOrganizationAcl.SecurityGroupID, existingOrganizationAcl.SecurityGroupID);
                }

                var count = await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM AclOrganizations WHERE OrganizationID = @OrganizationID AND SecurityGroupID = @SecurityGroupID AND PermissionID = @PermissionID)
	INSERT INTO AclOrganizations (OrganizationID, SecurityGroupID, PermissionID, Allowed, Overridden) VALUES (@OrganizationID, @SecurityGroupID, @PermissionID, @Allowed, 1)"    , new SqlParameter("OrganizationID", organization.ID), new SqlParameter("SecurityGroupID", SecurityGroupMap[existingOrganizationAcl.SecurityGroupID]), new SqlParameter("PermissionID", existingOrganizationAcl.PermissionID), new SqlParameter("Allowed", existingOrganizationAcl.Allowed));
            }

            //Org Event Acls
            var existingOrganizationEventAcls = await(from a in DataContext.OrganizationEvents where a.OrganizationID == existing.ID select a).ToArrayAsync();
            foreach (var existingOrganizationEventAcl in existingOrganizationEventAcls)
            {
                if (!SecurityGroupMap.ContainsKey(existingOrganizationEventAcl.SecurityGroupID))
                {
                    SecurityGroupMap.Add(existingOrganizationEventAcl.SecurityGroupID, existingOrganizationEventAcl.SecurityGroupID);
                }

                await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM OrganizationEvents WHERE OrganizationID = @OrganizationID AND SecurityGroupID = @SecurityGroupID AND EventID = @EventID)
	INSERT INTO OrganizationEvents (OrganizationID, SecurityGroupID, EventID, Allowed, Overridden) VALUES (@OrganizationID, @SecurityGroupID, @EventID, @Allowed, 0)"    , new SqlParameter("OrganizationID", organization.ID), new SqlParameter("SecurityGroupID", SecurityGroupMap[existingOrganizationEventAcl.SecurityGroupID]), new SqlParameter("EventID", existingOrganizationEventAcl.EventID), new SqlParameter("Allowed", existingOrganizationEventAcl.Allowed));
            }

            return(organization.ID);
        }
Ejemplo n.º 2
0
        public async Task <Guid> Copy(Guid organizationID)
        {
            var existing = await(from o in DataContext.Organizations where o.ID == organizationID select o).FirstOrDefaultAsync();

            if (existing == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The Organization could not be found."));
            }

            if (!await DataContext.HasPermissions <Organization>(Identity, existing.ID, PermissionIdentifiers.Organization.Copy))
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You do not have permission to copy the specified organization."));
            }

            string newAcronym = "New " + existing.Acronym;
            string newName    = "New " + existing.Name;

            while (await(from p in DataContext.Organizations where !p.Deleted && (p.Name == newName && p.Acronym == newAcronym) select p).AnyAsync())
            {
                newAcronym = "New " + newAcronym;
                newName    = "New " + newName;
            }

            var organization = new Organization
            {
                Acronym = newAcronym,
                Name    = newName,
                ParentOrganizationID          = existing.ParentOrganizationID,
                ApprovalRequired              = existing.ApprovalRequired,
                ContactEmail                  = existing.ContactEmail,
                ContactFirstName              = existing.ContactFirstName,
                ContactLastName               = existing.ContactLastName,
                ContactPhone                  = existing.ContactPhone,
                SpecialRequirements           = existing.SpecialRequirements,
                UsageRestrictions             = existing.UsageRestrictions,
                HealthPlanDescription         = existing.HealthPlanDescription,
                EnableClaimsAndBilling        = existing.EnableClaimsAndBilling,
                EnableEHRA                    = existing.EnableEHRA,
                EnableRegistries              = existing.EnableRegistries,
                DataModelESP                  = existing.DataModelESP,
                DataModelHMORNVDW             = existing.DataModelHMORNVDW,
                DataModelI2B2                 = existing.DataModelI2B2,
                DataModelMSCDM                = existing.DataModelMSCDM,
                DataModelOMOP                 = existing.DataModelOMOP,
                DataModelOther                = existing.DataModelOther,
                DataModelOtherText            = existing.DataModelOtherText,
                PragmaticClinicalTrials       = existing.PragmaticClinicalTrials,
                Biorepositories               = existing.Biorepositories,
                PatientReportedBehaviors      = existing.PatientReportedBehaviors,
                PatientReportedOutcomes       = existing.PatientReportedOutcomes,
                PrescriptionOrders            = existing.PrescriptionOrders,
                InpatientEHRApplication       = existing.InpatientEHRApplication,
                OutpatientEHRApplication      = existing.OutpatientEHRApplication,
                OtherInpatientEHRApplication  = existing.OtherInpatientEHRApplication,
                OtherOutpatientEHRApplication = existing.OtherOutpatientEHRApplication,
                InpatientClaims               = existing.InpatientClaims,
                OutpatientClaims              = existing.OutpatientClaims,
                ObservationalParticipation    = existing.ObservationalParticipation,
                ProspectiveTrials             = existing.ProspectiveTrials,
                EnrollmentClaims              = existing.EnrollmentClaims,
                DemographicsClaims            = existing.DemographicsClaims,
                LaboratoryResultsClaims       = existing.LaboratoryResultsClaims,
                VitalSignsClaims              = existing.LaboratoryResultsClaims,
                OtherClaims                   = existing.OtherClaims,
                OtherClaimsText               = existing.OtherClaimsText,
                ObservationClinicalExperience = existing.ObservationClinicalExperience
            };

            DataContext.Organizations.Add(organization);

            //Registries
            var existingRegistries = await(from reg in DataContext.OrganizationRegistries where reg.OrganizationID == existing.ID select reg).ToArrayAsync();

            foreach (var existingRegistry in existingRegistries)
            {
                var reg = new OrganizationRegistry
                {
                    RegistryID     = existingRegistry.RegistryID,
                    OrganizationID = organization.ID,
                    Description    = existingRegistry.Description
                };
                DataContext.OrganizationRegistries.Add(reg);
            }

            //EHRS
            foreach (var existingEHR in await DataContext.OrganizationEHRSes.Where(e => e.OrganizationID == existing.ID).ToArrayAsync())
            {
                DataContext.OrganizationEHRSes.Add(new OrganizationEHRS
                {
                    EndYear        = existingEHR.EndYear,
                    OrganizationID = organization.ID,
                    Other          = existingEHR.Other,
                    StartYear      = existingEHR.StartYear,
                    System         = existingEHR.System,
                    Type           = existingEHR.Type
                });
            }

            //Security Groups
            var existingSecurityGroups = await(from sg in DataContext.SecurityGroups.Include(x => x.Users) where sg.OwnerID == existing.ID orderby sg.ParentSecurityGroupID select sg).ToArrayAsync();
            var SecurityGroupMap       = new Dictionary <Guid, Guid>();

            CopySecurityGroups(existingSecurityGroups, ref SecurityGroupMap, null, organization);

            await DataContext.SaveChangesAsync();

            //All of these are done this way with a conditional if because the triggers cause inserts that entity framework is not aware of. Note that they are parameterized to ensure no sql injections.

            foreach (var user in existingSecurityGroups.SelectMany(u => u.Users).DistinctBy(u => new { u.SecurityGroupID, u.UserID }))
            {
                await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM SecurityGroupUsers WHERE UserID = @UserID AND SecurityGroupID = @SecurityGroupID)
	INSERT INTO SecurityGroupUsers (UserID, SecurityGroupID, Overridden) VALUES (@UserID, @SecurityGroupID, 0)"    , new SqlParameter("UserID", user.UserID), new SqlParameter("SecurityGroupID", SecurityGroupMap[user.SecurityGroupID]));

                //DataContext.SecurityGroupUsers.Add(new SecurityGroupUser
                //{
                //    Overridden = false,
                //    SecurityGroupID = SecurityGroupMap[user.SecurityGroupID],
                //    UserID = user.UserID
                //});
                //await DataContext.SaveChangesAsync();
            }



            //Org Acls
            var existingSecurityGroupIDs = SecurityGroupMap.Select(gm => gm.Key).ToArray();
            var existingOrganizationAcls = await(from a in DataContext.OrganizationAcls where a.OrganizationID == existing.ID && existingSecurityGroupIDs.Contains(a.SecurityGroupID) select a).Distinct().ToArrayAsync();

            foreach (var existingOrganizationAcl in existingOrganizationAcls)
            {
                if (!SecurityGroupMap.ContainsKey(existingOrganizationAcl.SecurityGroupID))
                {
                    SecurityGroupMap.Add(existingOrganizationAcl.SecurityGroupID, existingOrganizationAcl.SecurityGroupID);
                }

                var count = await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM AclOrganizations WHERE OrganizationID = @OrganizationID AND SecurityGroupID = @SecurityGroupID AND PermissionID = @PermissionID)
	INSERT INTO AclOrganizations (OrganizationID, SecurityGroupID, PermissionID, Allowed, Overridden) VALUES (@OrganizationID, @SecurityGroupID, @PermissionID, @Allowed, 1)"    , new SqlParameter("OrganizationID", organization.ID), new SqlParameter("SecurityGroupID", SecurityGroupMap[existingOrganizationAcl.SecurityGroupID]), new SqlParameter("PermissionID", existingOrganizationAcl.PermissionID), new SqlParameter("Allowed", existingOrganizationAcl.Allowed));

                //DataContext.OrganizationAcls.Add(new AclOrganization
                //{
                //    Allowed = existingOrganizationAcl.Allowed,
                //    Overridden = existingOrganizationAcl.Overridden,
                //    PermissionID = existingOrganizationAcl.PermissionID,
                //    OrganizationID = organization.ID,
                //    SecurityGroupID = SecurityGroupMap[existingOrganizationAcl.SecurityGroupID]
                //});

                //await DataContext.SaveChangesAsync();
            }

            //Org Event Acls
            var existingOrganizationEventAcls = await(from a in DataContext.OrganizationEvents where a.OrganizationID == existing.ID select a).ToArrayAsync();

            foreach (var existingOrganizationEventAcl in existingOrganizationEventAcls)
            {
                if (!SecurityGroupMap.ContainsKey(existingOrganizationEventAcl.SecurityGroupID))
                {
                    SecurityGroupMap.Add(existingOrganizationEventAcl.SecurityGroupID, existingOrganizationEventAcl.SecurityGroupID);
                }

                await DataContext.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM OrganizationEvents WHERE OrganizationID = @OrganizationID AND SecurityGroupID = @SecurityGroupID AND EventID = @EventID)
	INSERT INTO OrganizationEvents (OrganizationID, SecurityGroupID, EventID, Allowed, Overridden) VALUES (@OrganizationID, @SecurityGroupID, @EventID, @Allowed, 0)"    , new SqlParameter("OrganizationID", organization.ID), new SqlParameter("SecurityGroupID", SecurityGroupMap[existingOrganizationEventAcl.SecurityGroupID]), new SqlParameter("EventID", existingOrganizationEventAcl.EventID), new SqlParameter("Allowed", existingOrganizationEventAcl.Allowed));
            }

            return(organization.ID);
        }