Пример #1
0
        /// <inheritdoc/>
        public async Task <Instance> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid   instanceGuid    = Guid.NewGuid();
            string appName         = startServiceModel.Service;
            string org             = startServiceModel.Org;
            int    instanceOwnerId = startServiceModel.PartyId;
            int    userId          = startServiceModel.UserId;

            ServiceState currentTask = _workflow.GetInitialServiceState(org, appName);

            Instance instance = new Instance
            {
                Id = $"{instanceOwnerId}/{instanceGuid}",
                InstanceOwnerId = instanceOwnerId.ToString(),
                AppId           = $"{org}/{appName}",
                Org             = org,
                CreatedBy       = userId.ToString(),
                CreatedDateTime = DateTime.UtcNow,
                Process         = new Storage.Interface.Models.ProcessState()
                {
                    CurrentTask = currentTask.State.ToString(),
                    IsComplete  = false,
                },
                InstanceState = new Storage.Interface.Models.InstanceState()
                {
                    IsArchived            = false,
                    IsDeleted             = false,
                    IsMarkedForHardDelete = false,
                },
                LastChangedDateTime = DateTime.UtcNow,
                LastChangedBy       = userId.ToString(),
            };

            string developer         = AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext);
            string testDataForParty  = $"{_settings.GetTestdataForPartyPath(org, appName, developer)}{instanceOwnerId}";
            string folderForInstance = Path.Combine(testDataForParty, instanceGuid.ToString());

            Directory.CreateDirectory(folderForInstance);
            string instanceFilePath = $"{testDataForParty}/{instanceGuid}/{instanceGuid}.json";

            File.WriteAllText(instanceFilePath, JsonConvert.SerializeObject(instance).ToString(), Encoding.UTF8);

            // Save instantiated form model
            instance = await _data.InsertData(
                serviceModel,
                instanceGuid,
                serviceImplementation.GetServiceModelType(),
                org,
                appName,
                instanceOwnerId);

            return(instance);
        }
Пример #2
0
        /// <inheritdoc />
        public async Task <Instance> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid     instanceId;
            Instance instance        = null;
            string   org             = startServiceModel.Org;
            string   appId           = ApplicationHelper.GetFormattedApplicationId(org, startServiceModel.Service);
            string   appName         = startServiceModel.Service;
            int      instanceOwnerId = startServiceModel.PartyId;

            string apiUrl = $"instances/?appId={appId}&instanceOwnerId={instanceOwnerId}";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            try
            {
                HttpResponseMessage response = await _client.PostAsync(apiUrl, new StringContent("{}", Encoding.UTF8, "application/json"));

                Instance createdInstance = await response.Content.ReadAsAsync <Instance>();

                instanceId = Guid.Parse(createdInstance.Id.Split("/")[1]);
            }
            catch
            {
                return(instance);
            }

            // Save instantiated form model
            instance = await _data.InsertData(
                serviceModel,
                instanceId,
                serviceImplementation.GetServiceModelType(),
                org,
                appName,
                instanceOwnerId);

            ServiceState currentState = _workflow.GetInitialServiceState(org, appName);

            // set initial workflow state
            instance.Process = new Storage.Interface.Models.ProcessState()
            {
                CurrentTask = currentState.State.ToString(),
                IsComplete  = false,
            };

            instance = await UpdateInstance(instance, appName, org, instanceOwnerId, instanceId);

            return(instance);
        }
Пример #3
0
        /// <inheritdoc />
        public async Task <Instance> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid     instanceId;
            Instance instance           = null;
            string   applicationOwnerId = startServiceModel.Org;
            string   applicationId      = ApplicationHelper.GetFormattedApplicationId(applicationOwnerId, startServiceModel.Service);
            int      instanceOwnerId    = startServiceModel.ReporteeID;

            using (HttpClient client = new HttpClient())
            {
                string apiUrl = $"{_platformSettings.GetApiStorageEndpoint}instances/?applicationId={applicationId}&instanceOwnerId={instanceOwnerId}";
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    HttpResponseMessage response = await client.PostAsync(apiUrl, null);

                    string id = await response.Content.ReadAsAsync <string>();

                    instanceId = Guid.Parse(id);
                }
                catch
                {
                    return(instance);
                }
            }

            // Save instantiated form model
            instance = await _data.InsertData(
                serviceModel,
                instanceId,
                serviceImplementation.GetServiceModelType(),
                applicationOwnerId,
                applicationId,
                instanceOwnerId);

            ServiceState currentState = _workflow.GetInitialServiceState(applicationOwnerId, applicationId);

            // set initial workflow state
            instance.CurrentWorkflowStep = currentState.State.ToString();

            instance = await UpdateInstance(instance, applicationId, applicationOwnerId, instanceOwnerId, instanceId);

            return(instance);
        }
Пример #4
0
        public async Task <Instance> InstantiateInstance(StartServiceModel startServiceModel, object serviceModel, IServiceImplementation serviceImplementation)
        {
            Guid     instanceId;
            Instance instance        = null;
            string   org             = startServiceModel.Org;
            string   app             = startServiceModel.Service;
            int      instanceOwnerId = startServiceModel.PartyId;

            Instance instanceTemplate = new Instance()
            {
                InstanceOwnerId = instanceOwnerId.ToString(),
                Process         = new ProcessState()
                {
                    Started     = DateTime.UtcNow,
                    CurrentTask = new ProcessElementInfo
                    {
                        Started = DateTime.UtcNow,

                        ElementId = _workflow.GetInitialServiceState(org, app).State.ToString(),
                    }
                },
            };

            Instance createdInstance = await CreateInstance(org, app, instanceTemplate);

            if (createdInstance == null)
            {
                return(null);
            }

            instanceId = Guid.Parse(createdInstance.Id.Split("/")[1]);

            // Save instantiated form model
            instance = await _data.InsertFormData(
                serviceModel,
                instanceId,
                serviceImplementation.GetServiceModelType(),
                org,
                app,
                instanceOwnerId);

            instance = await UpdateInstance(instance, app, org, instanceOwnerId, instanceId);

            return(instance);
        }
Пример #5
0
        public async Task <ActionResult <Instance> > Post(
            [FromRoute] string org,
            [FromRoute] string app,
            [FromQuery] int?instanceOwnerId)
        {
            if (string.IsNullOrEmpty(org))
            {
                return(BadRequest("The path parameter 'org' cannot be empty"));
            }

            if (string.IsNullOrEmpty(app))
            {
                return(BadRequest("The path parameter 'app' cannot be empty"));
            }

            Application application = repositoryService.GetApplication(org, app);

            if (application == null)
            {
                return(NotFound($"AppId {org}/{app} was not found"));
            }

            MultipartRequestReader parsedRequest = new MultipartRequestReader(Request);

            parsedRequest.Read().Wait();

            if (parsedRequest.Errors.Any())
            {
                return(BadRequest($"Error when reading content: {parsedRequest.Errors}"));
            }

            Instance instanceTemplate = ExtractInstanceTemplate(parsedRequest);

            if (!instanceOwnerId.HasValue && instanceTemplate == null)
            {
                return(BadRequest("Cannot create an instance without an instanceOwnerId. Either provide instanceOwnerId as a query parameter or an instanceTemplate object in the body."));
            }

            if (instanceOwnerId.HasValue && instanceTemplate != null)
            {
                return(BadRequest("You cannot provide an instanceOwnerId as a query param as well as an instance template in the body. Choose one or the other."));
            }

            RequestPartValidator requestValidator = new RequestPartValidator(application);

            string multipartError = requestValidator.ValidateParts(parsedRequest.Parts);

            if (!string.IsNullOrEmpty(multipartError))
            {
                return(BadRequest($"Error when comparing content to application metadata: {multipartError}"));
            }

            // extract or create instance template
            if (instanceTemplate != null)
            {
                InstanceOwnerLookup lookup = instanceTemplate.InstanceOwnerLookup;

                if (string.IsNullOrEmpty(instanceTemplate.InstanceOwnerId) && (lookup == null || (lookup.PersonNumber == null && lookup.OrganisationNumber == null)))
                {
                    return(BadRequest($"Error: instanceOwnerId is empty and InstanceOwnerLookup is missing. You must populate instanceOwnerId or InstanceOwnerLookup"));
                }
            }
            else
            {
                instanceTemplate = new Instance();
                instanceTemplate.InstanceOwnerId = instanceOwnerId.Value.ToString();
            }

            Party party = null;

            if (instanceTemplate.InstanceOwnerId != null)
            {
                party = await registerService.GetParty(int.Parse(instanceTemplate.InstanceOwnerId));
            }
            else
            {
                /* todo - lookup personNumber or organisationNumber - awaiting registry endpoint implementation */
            }

            if (!InstantiationHelper.IsPartyAllowedToInstantiate(party, application.PartyTypesAllowed))
            {
                return(Forbid($"Party {party?.PartyId} is not allowed to instantiate this application {org}/{app}"));
            }

            // set initial task
            instanceTemplate.Process = instanceTemplate.Process ?? new ProcessState()
            {
                Started     = DateTime.UtcNow,
                CurrentTask = new TaskInfo
                {
                    Started          = DateTime.UtcNow,
                    ProcessElementId = processService.GetInitialServiceState(org, app).State.ToString(),
                }
            };

            Instance instance = null;

            try
            {
                instance = await instanceService.CreateInstance(org, app, instanceTemplate);

                if (instance == null)
                {
                    throw new PlatformClientException("Failure instantiating instance. UnknownError");
                }
            }
            catch (Exception instanceException)
            {
                string message = $"Failure in multpart prefil. Could not create an instance of {org}/{app} for {instanceOwnerId}. App-backend has problem accessing platform storage.";

                logger.LogError($"{message} - {instanceException}");
                return(StatusCode(500, $"{message} - {instanceException.Message}"));
            }

            try
            {
                Instance instanceWithData = await StorePrefillParts(instance, parsedRequest.Parts);

                if (instanceWithData != null)
                {
                    instance = instanceWithData;
                }
            }
            catch (Exception dataException)
            {
                string message = $"Failure storing multpart prefil. Could not create a data element for {instance.Id} of {org}/{app}. App-backend has problem accessing platform storage.";
                logger.LogError($"{message} - {dataException}");

                // todo add compensating transaction (delete instance)
                return(StatusCode(500, $"{message} - {dataException.Message}"));
            }

            SetAppSelfLinks(instance, Request);
            string url = instance.SelfLinks.Apps;

            await DispatchEvent(InstanceEventType.Created.ToString(), instance);

            return(Created(url, instance));
        }