Ejemplo n.º 1
0
        public OrganizationVersioned SaveOrganization(IUnitOfWorkWritable unitOfWork, VmOrganizationInput model)
        {
            var organizationRep = unitOfWork.CreateRepository <IOrganizationVersionedRepository>();
            var unificRootId    = versionManager.GetUnificRootId <OrganizationVersioned>(unitOfWork, model.Id);

            if (unificRootId.HasValue && IsCyclicDependency(unitOfWork, unificRootId.Value, model.ParentId))
            {
                throw new OrganizationCyclicDependencyException();
            }
            if (!string.IsNullOrEmpty(model.OrganizationId) && organizationRep.All().Any(x => (x.UnificRootId != unificRootId) && (x.Oid == model.OrganizationId)))
            {
                throw new PtvArgumentException("", model.OrganizationId);
            }

            if (typesCache.Get <OrganizationType>(OrganizationTypeEnum.TT1.ToString()) == model.OrganizationType ||
                typesCache.Get <OrganizationType>(OrganizationTypeEnum.TT2.ToString()) == model.OrganizationType)
            {
                if (organizationRep.All().Single(x => x.Id == model.Id).TypeId != model.OrganizationType)
                {
                    throw new PtvServiceArgumentException("Organization type is not allowed!", new List <string> {
                        typesCache.GetByValue <OrganizationType>(model.OrganizationType.Value)
                    });
                }
            }
            var entity = TranslationManagerToEntity.Translate <VmOrganizationInput, OrganizationVersioned>(model, unitOfWork);

            unitOfWork.Save();


            return(entity);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Updates service connections related to defined service channel. This is a method only for ASTI so ASTI rules are added.
        /// See ASTI rules from page https://confluence.csc.fi/display/PAL/ASTI-project and https://jira.csc.fi/browse/PTV-2065.
        /// </summary>
        /// <param name="request">The connection model</param>
        /// <param name="openApiVersion">The open api version to be returned.</param>
        /// <returns>Updated service channel with connection information</returns>
        public IVmOpenApiServiceChannel SaveServiceChannelConnections(V7VmOpenApiChannelServicesIn relations, int openApiVersion)
        {
            if (relations == null)
            {
                return(null);
            }

            var rootID = relations.ChannelId.Value;

            try
            {
                contextManager.ExecuteWriter(unitOfWork =>
                {
                    var serviceChannel = TranslationManagerToEntity.Translate <V7VmOpenApiChannelServicesIn, ServiceChannel>(relations, unitOfWork);
                    // We need to manually remove ASTI connections from collection. All other connections should stay as they are.
                    var updatedConnections  = relations.ServiceRelations?.Count > 0 ? relations.ServiceRelations.Select(r => r.ServiceGuid).ToList() : new List <Guid>();
                    var astiConnections     = serviceChannel.ServiceServiceChannels.Where(c => c.IsASTIConnection == true).ToList();
                    var connectionsToRemove = astiConnections.Where(a => !updatedConnections.Contains(a.ServiceId)).ToList();
                    RemoveConnections(unitOfWork, connectionsToRemove);

                    unitOfWork.Save();
                });
            }
            catch (Exception ex)
            {
                var errorMsg = $"Error occured while updating relations for a service channel with id {rootID}. {ex.Message}";
                logger.LogError(errorMsg + " " + ex.StackTrace);
                throw new Exception(errorMsg);
            }

            return(channelService.GetServiceChannelById(rootID, openApiVersion, VersionStatusEnum.Latest));
        }
Ejemplo n.º 3
0
        public VmFormState Save(VmFormState formState)
        {
            VmFormState result = null;

            contextManager.ExecuteWriter(unitOfWork =>
            {
                var formStateRepository = unitOfWork.CreateRepository <IFormStateRepository>();
                var isExistingFormState = formState.Id != null;
                if (isExistingFormState)
                {
                    var existingFormState = formStateRepository.All()
                                            .Where(x => x.Id == new Guid(formState.Id))
                                            .FirstOrDefault();
                    existingFormState.State = formState.State;
                    unitOfWork.Save();
                    result = TranslationManagerToVm.Translate <FormState, VmFormState>(existingFormState);
                }
                else
                {
                    var formStateToSave = TranslationManagerToEntity.Translate <VmFormState, FormState>(formState, unitOfWork);
                    formStateRepository.Add(formStateToSave);
                    unitOfWork.Save();
                    result = TranslationManagerToVm.Translate <FormState, VmFormState>(formStateToSave);
                }
            });
            return(result);
        }
Ejemplo n.º 4
0
        private void SaveRelations(IUnitOfWorkWritable unitOfWork, VmConnectionsInput model)
        {
            var unificRootId = versioningManager.GetUnificRootId <ServiceVersioned>(unitOfWork, model.Id);

            if (unificRootId.HasValue)
            {
                model.UnificRootId = unificRootId.Value;
                TranslationManagerToEntity.Translate <VmConnectionsInput, Service>(model, unitOfWork);
            }
        }
Ejemplo n.º 5
0
 public void SaveBugReport(VmBugReport vm)
 {
     contextManager.ExecuteWriter(unitOfWork =>
     {
         var bugReport           = TranslationManagerToEntity.Translate <VmBugReport, BugReport>(vm, unitOfWork);
         var bugReportRepository = unitOfWork.CreateRepository <IBugReportRepository>();
         bugReportRepository.Add(bugReport);
         unitOfWork.Save(parentEntity: bugReport);
     });
 }
Ejemplo n.º 6
0
        private ServiceCollectionVersioned DeleteServiceCollection(IUnitOfWorkWritable unitOfWork, Guid?serviceCollectionId)
        {
            var publishStatus = TranslationManagerToEntity.Translate <String, PublishingStatusType>(PublishingStatus.Deleted.ToString(), unitOfWork);

            var serviceCollectionRep = unitOfWork.CreateRepository <IServiceCollectionVersionedRepository>();
            var serviceCollection    = serviceCollectionRep.All().Single(x => x.Id == serviceCollectionId.Value);

            serviceCollection.PublishingStatus = publishStatus;

            return(serviceCollection);
        }
Ejemplo n.º 7
0
 private ServiceVersioned SaveService(IUnitOfWorkWritable unitOfWork, VmServiceInput model)
 {
     if (model.GeneralDescriptionId.HasValue)
     {
         var gdRep = unitOfWork.CreateRepository <IStatutoryServiceGeneralDescriptionVersionedRepository>();
         var gd    = unitOfWork.ApplyIncludes(gdRep.All()
                                              .Where(x => x.UnificRootId == model.GeneralDescriptionId)
                                              .OrderBy(x => x.PublishingStatus.PriorityFallback), i => i.Include(x => x.PublishingStatus))
                     .FirstOrDefault();
         model.GeneralDescriptionServiceTypeId = gd?.TypeId;
         model.GeneralDescriptionChargeTypeId  = gd?.ChargeTypeId;
     }
     return(TranslationManagerToEntity.Translate <VmServiceInput, ServiceVersioned>(model, unitOfWork));
 }
Ejemplo n.º 8
0
        private string SaveServiceServiceChannel(V7VmOpenApiServiceServiceChannelAstiInBase serviceServiceChannel)
        {
            if (!serviceServiceChannel.ChannelGuid.IsAssigned())
            {
                serviceServiceChannel.ChannelGuid = serviceServiceChannel.ServiceChannelId.ParseToGuidWithExeption();
                serviceServiceChannel.ServiceGuid = serviceServiceChannel.ServiceId.ParseToGuidWithExeption();
            }

            var currentVersion = serviceService.GetServiceByIdSimple(serviceServiceChannel.ServiceGuid);

            if (currentVersion == null || string.IsNullOrEmpty(currentVersion.PublishingStatus))
            {
                return(string.Format(CoreMessages.OpenApi.EntityNotFound, "Service", serviceServiceChannel.ServiceGuid));
            }
            else if (currentVersion.PublishingStatus != PublishingStatus.Draft.ToString() && currentVersion.PublishingStatus != PublishingStatus.Published.ToString())
            {
                return($"Publishing status for service '{serviceServiceChannel.ServiceGuid}' is {currentVersion.PublishingStatus}. You cannot update service!");
            }

            var channel = channelService.GetServiceChannelByIdSimple(serviceServiceChannel.ChannelGuid);

            if (channel == null || !channel.Id.IsAssigned())
            {
                return(string.Format(CoreMessages.OpenApi.EntityNotFound, "Service channel", serviceServiceChannel.ChannelGuid));
            }

            string msg = null;

            contextManager.ExecuteWriter(unitOfWork =>
            {
                try
                {
                    CheckChannelData(unitOfWork, serviceServiceChannel.ChannelGuid, serviceServiceChannel.IsASTIConnection, serviceServiceChannel.ServiceHours, serviceServiceChannel.ContactDetails);

                    var result = TranslationManagerToEntity.Translate <IVmOpenApiServiceServiceChannelInVersionBase, ServiceServiceChannel>(serviceServiceChannel, unitOfWork);

                    unitOfWork.Save();
                    msg = string.Format(CoreMessages.OpenApi.ServiceServiceChannelAdded, serviceServiceChannel.ChannelGuid, serviceServiceChannel.ServiceGuid);
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                }
            });

            return(msg);
        }
Ejemplo n.º 9
0
        public IVmOpenApiServiceCollectionBase AddServiceCollection(IVmOpenApiServiceCollectionInVersionBase vm, bool allowAnonymous, int openApiVersion, string userName = null)
        {
            var serviceCollection = new ServiceCollectionVersioned();
            var saveMode          = allowAnonymous ? SaveMode.AllowAnonymous : SaveMode.Normal;
            var userId            = userName ?? utilities.GetRelationIdForExternalSource();
            var useOtherEndPoint  = false;

            contextManager.ExecuteWriter(unitOfWork =>
            {
                // Check if the external source already exists. Let's not throw the excpetion here to avoid contextManager to catch the exception.
                useOtherEndPoint = ExternalSourceExists <ServiceCollection>(vm.SourceId, userId, unitOfWork);
                if (!useOtherEndPoint)
                {
                    serviceCollection = TranslationManagerToEntity.Translate <IVmOpenApiServiceCollectionInVersionBase, ServiceCollectionVersioned>(vm, unitOfWork);

                    var serviceCollectionRep = unitOfWork.CreateRepository <IServiceCollectionVersionedRepository>();
                    serviceCollectionRep.Add(serviceCollection);

                    // Create the mapping between external source id and PTV id
                    if (!string.IsNullOrEmpty(vm.SourceId))
                    {
                        SetExternalSource(serviceCollection.UnificRoot, vm.SourceId, userId, unitOfWork);
                    }

                    unitOfWork.Save(saveMode, userName: userName);
                }
            });

            if (useOtherEndPoint)
            {
                throw new ExternalSourceExistsException(string.Format(CoreMessages.OpenApi.ExternalSourceExists, vm.SourceId));
            }

            // Publish all language versions
            if (vm.PublishingStatus == PublishingStatus.Published.ToString())
            {
                var publishingResult = commonService.PublishAllAvailableLanguageVersions <ServiceCollectionVersioned, ServiceCollectionLanguageAvailability>(serviceCollection.Id, i => i.ServiceCollectionVersionedId == serviceCollection.Id);
            }

            return(GetServiceCollectionWithDetails(serviceCollection.Id, openApiVersion, false));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Updates channel connections for a defined service. This is used for both ASTI and regular connections
        /// Regular users can update data within ASTI connections but they cannot remove any ASTI connections.
        /// ASTI users can remove and update ASTI connections - regular connections are not removed.
        /// More rules in https://confluence.csc.fi/display/PAL/ASTI-project and https://jira.csc.fi/browse/PTV-2065.
        /// </summary>
        /// <param name="relations">The connection model</param>
        /// <param name="openApiVersion">The open api version to be returned.</param>
        /// <returns>Updated service with connection information</returns>
        public IVmOpenApiServiceVersionBase SaveServiceConnections(V7VmOpenApiServiceAndChannelRelationAstiInBase relations, int openApiVersion)
        {
            if (relations == null)
            {
                return(null);
            }

            Service service;
            var     rootID = relations.ServiceId.Value;

            try
            {
                contextManager.ExecuteWriter(unitOfWork =>
                {
                    service = TranslationManagerToEntity.Translate <V7VmOpenApiServiceAndChannelRelationAstiInBase, Service>(relations, unitOfWork);
                    // We need to manually remove right connections from collection.
                    // If connections are ASTI connections regular connections should stay as they are.
                    // If connections are regular connections ASTI connections should stay as they are - the data can be updated though (except extraTypes).
                    var updatedConnectionIds = relations.ChannelRelations?.Count > 0 ? relations.ChannelRelations.Select(r => r.ChannelGuid).ToList() : new List <Guid>();
                    var updatedConnections   = service.ServiceServiceChannels.Where(c => updatedConnectionIds.Contains(c.ServiceChannelId)).ToList();
                    var connections          = service.ServiceServiceChannels.Where(c => c.IsASTIConnection == relations.IsASTI).ToList();
                    var connectionsToRemove  = connections.Where(a => !updatedConnectionIds.Contains(a.ServiceChannelId)).ToList();
                    RemoveConnections(unitOfWork, connectionsToRemove);

                    unitOfWork.Save();
                });
            }
            catch (Exception ex)
            {
                var errorMsg = $"Error occured while updating relations for a service with id {rootID}. {ex.Message}";
                logger.LogError(errorMsg + " " + ex.StackTrace);
                throw new Exception(errorMsg);
            }

            return(serviceService.GetServiceById(rootID, openApiVersion, VersionStatusEnum.Latest));
        }
Ejemplo n.º 11
0
        public List <IVmBase> SaveServiceAndChannels(VmRelations relations)
        {
            var result = new List <IVmBase>();

            Dictionary <Guid, Guid> serviceVersion = new Dictionary <Guid, Guid>();

            contextManager.ExecuteWriter(unitOfWork =>
            {
                IQueryable <Guid> supportedChannelIds = null;
                var userOrgs = userOrganizationService.GetUserCompleteOrgStructure(unitOfWork);
                if (userOrganizationService.UserHighestRole(userOrgs) != UserRoleEnum.Eeva)
                {
                    var schvRep        = unitOfWork.CreateRepository <IServiceChannelVersionedRepository>();
                    var userOrgsIds    = userOrgs.SelectMany(i => i).Select(i => i.OrganizationId).ToList();
                    var psPublished    = typesCache.Get <PublishingStatusType>(PublishingStatus.Published.ToString());
                    var psCommonForAll = typesCache.Get <ServiceChannelConnectionType>(ServiceChannelConnectionTypeEnum.CommonForAll.ToString());
                    var channelIds     = relations.ServiceAndChannelRelations.SelectMany(r => r.ChannelRelations).Select(ch => ch.ConnectedChannel.Id);
                    var channels       = schvRep.All().Where(i => channelIds.Contains(i.Id));

                    var supportedChannels = channels.Where(ch => (userOrgsIds.Contains(ch.OrganizationId) || (ch.PublishingStatusId == psPublished && ch.ConnectionTypeId == psCommonForAll)));

                    supportedChannelIds = supportedChannels.Select(ch => ch.UnificRootId);
                }

                SetTranslatorLanguage(relations);
                relations.ServiceAndChannelRelations = relations.ServiceAndChannelRelations.Distinct(new RelationComparer()).ToList();
                relations.ServiceAndChannelRelations.ForEach(i => i.ChannelRelations = i.ChannelRelations.Distinct(new RelationChannelsComparer()).ToList());

                var serviceVersionedRep = unitOfWork.CreateRepository <IServiceVersionedRepository>();
                var serviceVersionedIds = relations.ServiceAndChannelRelations.Select(sv => sv.Id).ToList();
                var unificRootIds       = serviceVersionedRep.All().Where(sv => serviceVersionedIds.Contains(sv.Id)).ToDictionary(k => k.Id, v => v.UnificRootId);
                foreach (var item in relations.ServiceAndChannelRelations)
                {
                    if (!item.Id.IsAssigned() || !unificRootIds.ContainsKey(item.Id.Value))
                    {
                        continue;
                    }
                    item.UnificRootId = unificRootIds[item.Id.Value];
                    item.ChannelRelations.ForEach(chs => chs.Service = unificRootIds[item.Id.Value]);
                }


                var relationData = TranslationManagerToEntity.TranslateAll <VmServiceChannelRelation, Service>(relations.ServiceAndChannelRelations, unitOfWork);
                serviceVersion   = unitOfWork.TranslationCloneCache.GetFromCachedSet <ServiceVersioned>().ToDictionary(i => i.OriginalEntity.Id, i => i.ClonedEntity.Id);

                foreach (var service in relationData)
                {
                    var supportedServiceServiceChannels = supportedChannelIds == null
                                                ? service.ServiceServiceChannels
                        : service.ServiceServiceChannels.Where(ch => supportedChannelIds.Contains(ch.ServiceChannelId)).ToList();

                    service.ServiceServiceChannels = dataUtils.UpdateCollectionForReferenceTable(unitOfWork, supportedServiceServiceChannels, query => query.ServiceId == service.Id, channel => channel.ServiceChannelId);
                    UpdateDigitalAuthorizationCollection(unitOfWork, service.ServiceServiceChannels);
                }

                unitOfWork.Save();
            });

            contextManager.ExecuteReader(unitOfWork =>
            {
                var serviceCloneData = new Dictionary <Guid, string>();
                relations.ServiceAndChannelRelations.ForEach(service =>
                {
                    if (serviceVersion.ContainsKey(service.Id.Value))
                    {
                        serviceCloneData.Add(serviceVersion[service.Id.Value], service.ConnectedServiceId);
                    }
                });
                var cloneServiceIds = serviceCloneData.Select(y => y.Key).ToList();

                var serviceRep = unitOfWork.CreateRepository <IServiceVersionedRepository>();
                var resultTemp = unitOfWork.ApplyIncludes(serviceRep.All().Where(x => cloneServiceIds.Contains(x.Id)), q =>
                                                          q.Include(i => i.ServiceNames).ThenInclude(i => i.Type)
                                                          .Include(i => i.UnificRoot).ThenInclude(i => i.ServiceServiceChannels).ThenInclude(i => i.ServiceChannel).ThenInclude(i => i.Versions).ThenInclude(i => i.ServiceChannelNames).ThenInclude(i => i.Type)
                                                          .Include(i => i.UnificRoot).ThenInclude(i => i.ServiceServiceChannels).ThenInclude(i => i.ServiceChannel).ThenInclude(i => i.Versions).ThenInclude(i => i.Type)
                                                          .Include(i => i.UnificRoot).ThenInclude(i => i.ServiceServiceChannels).ThenInclude(i => i.ServiceServiceChannelDescriptions).ThenInclude(i => i.Type)
                                                          .Include(i => i.UnificRoot).ThenInclude(i => i.ServiceServiceChannels).ThenInclude(i => i.ServiceServiceChannelDigitalAuthorizations).ThenInclude(i => i.DigitalAuthorization)
                                                          );

                var cloneServices = TranslationManagerToVm.TranslateAll <ServiceVersioned, VmServiceRelationListItem>(resultTemp).Cast <IVmServiceListItem>().ToList();

                cloneServices.ForEach(service =>
                {
                    if (serviceCloneData.ContainsKey(service.Id))
                    {
                        result.Add(new VmConnectedService()
                        {
                            UiId = serviceCloneData[service.Id], Service = service
                        });
                    }
                });
            });
            return(result);
        }
Ejemplo n.º 12
0
        public IVmOpenApiServiceCollectionBase SaveServiceCollection(IVmOpenApiServiceCollectionInVersionBase vm, bool allowAnonymous, int openApiVersion, string sourceId = null, string userName = null)
        {
            var saveMode = allowAnonymous ? SaveMode.AllowAnonymous : SaveMode.Normal;
            var userId   = userName ?? utilities.GetRelationIdForExternalSource();
            IVmOpenApiServiceCollectionBase result            = new VmOpenApiServiceCollectionBase();
            ServiceCollectionVersioned      serviceCollection = null;

            contextManager.ExecuteWriter(unitOfWork =>
            {
                // Get the root id according to source id (if defined)
                var rootId = vm.Id ?? GetPTVId <ServiceCollection>(sourceId, userId, unitOfWork);

                // Get right version id
                vm.Id = versioningManager.GetVersionId <ServiceCollectionVersioned>(unitOfWork, rootId);

                if (vm.PublishingStatus == PublishingStatus.Deleted.ToString())
                {
                    serviceCollection = DeleteServiceCollection(unitOfWork, vm.Id);
                }
                else
                {
                    // Entity needs to be restored?
                    if (vm.CurrentPublishingStatus == PublishingStatus.Deleted.ToString())
                    {
                        if (vm.PublishingStatus == PublishingStatus.Modified.ToString() || vm.PublishingStatus == PublishingStatus.Published.ToString())
                        {
                            // We need to restore already archived item
                            var publishingResult = commonService.RestoreArchivedEntity <ServiceCollectionVersioned>(unitOfWork, vm.Id.Value);
                        }
                    }

                    serviceCollection = TranslationManagerToEntity.Translate <IVmOpenApiServiceCollectionInVersionBase, ServiceCollectionVersioned>(vm, unitOfWork);

                    if (vm.CurrentPublishingStatus == PublishingStatus.Draft.ToString())
                    {
                        // We need to manually remove items from collections!
                        if (vm.ServiceCollectionNames?.Count > 0)
                        {
                            var updatedEntities = serviceCollection.ServiceCollectionNames;
                            var rep             = unitOfWork.CreateRepository <IServiceCollectionNameRepository>();
                            var currentItems    = rep.All().Where(s => s.ServiceCollectionVersionedId == serviceCollection.Id).ToList();
                            var toRemove        = currentItems.Where(i => !updatedEntities.Any(s => s.TypeId == i.TypeId && s.LocalizationId == i.LocalizationId));
                            toRemove.ForEach(i => rep.Remove(i));
                        }
                        if (vm.ServiceCollectionDescriptions?.Count > 0)
                        {
                            var updatedEntities = serviceCollection.ServiceCollectionDescriptions;
                            var rep             = unitOfWork.CreateRepository <IServiceCollectionDescriptionRepository>();
                            var currentItems    = rep.All().Where(s => s.ServiceCollectionVersionedId == serviceCollection.Id).ToList();
                            var toRemove        = currentItems.Where(i => !updatedEntities.Any(s => s.TypeId == i.TypeId && s.LocalizationId == i.LocalizationId));
                            toRemove.ForEach(i => rep.Remove(i));
                        }
                        if (vm.DeleteAllServices || vm.ServiceCollectionServices?.Count > 0)
                        {
                            serviceCollection.ServiceCollectionServices = dataUtils.UpdateCollectionForReferenceTable(unitOfWork,
                                                                                                                      serviceCollection.ServiceCollectionServices,
                                                                                                                      query => query.ServiceCollectionVersionedId == serviceCollection.Id,
                                                                                                                      service => service.Service != null ? service.Service.Id : service.ServiceId
                                                                                                                      );
                        }
                    }

                    // Update the mapping between external source id and PTV id
                    if (!string.IsNullOrEmpty(vm.SourceId))
                    {
                        UpdateExternalSource <ServiceCollection>(serviceCollection.UnificRootId, vm.SourceId, userId, unitOfWork);
                    }
                }

                unitOfWork.Save(saveMode, serviceCollection, userName);
            });

            // Publish all language versions
            if (vm.PublishingStatus == PublishingStatus.Published.ToString())
            {
                var publishingResult = commonService.PublishAllAvailableLanguageVersions <ServiceCollectionVersioned, ServiceCollectionLanguageAvailability>(serviceCollection.Id, i => i.ServiceCollectionVersionedId == serviceCollection.Id);
            }

            return(GetServiceCollectionWithDetails(serviceCollection.Id, openApiVersion, false));
        }