예제 #1
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));
        }
예제 #2
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);
        }
예제 #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);
        }
예제 #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);
            }
        }
예제 #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);
     });
 }
예제 #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);
        }
예제 #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));
 }
예제 #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);
        }
예제 #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));
        }
예제 #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));
        }
예제 #11
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));
        }