public async Task <ActionResult> GetInstanceIncludeParty(int instanceOwnerId, Guid instanceGuid, bool includeParty = false) { ExtendedInstance result = new ExtendedInstance(); try { Instance instance = await _storage.GetInstance(instanceOwnerId, instanceGuid); result.Instance = instance; } catch (PlatformHttpException e) { return(HandlePlatformHttpException(e)); } string partyId = result?.Instance?.InstanceOwner?.PartyId; if (includeParty && partyId != null && int.TryParse(partyId, out int partyIdInt)) { try { Party party = await _register.GetParty(partyIdInt); result.Party = party; } catch (PlatformHttpException e) { return(HandlePlatformHttpException(e)); } } return(Ok(result)); }
/// <summary> /// Run events related to instantiation /// </summary> /// <remarks> /// For example custom prefill. /// </remarks> /// <param name="instance">Instance information</param> /// <param name="data">The data object created</param> public async Task DataCreation(Instance instance, object data) { if (data.GetType() == typeof(Skjema)) { Skjema model = (Skjema)data; int partyId; if (int.TryParse(instance.InstanceOwner.PartyId, out partyId)) { Party party = await _registerService.GetParty(partyId); model.Innledninggrp9309 = new Innledninggrp9309() { Kontaktinformasjongrp9311 = new Kontaktinformasjongrp9311() { MelderFultnavn = new MelderFultnavn() { value = party.Name } } }; } } await Task.CompletedTask; }
/// <inheritdoc/> public async Task GenerateAndStoreReceiptPDF(Instance instance) { string app = instance.AppId.Split("/")[1]; string org = instance.Org; int instanceOwnerId = int.Parse(instance.InstanceOwner.PartyId); Application application = _appResourcesService.GetApplication(); Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); DataType dataModelDataElement = application.DataTypes.Find(element => element.AppLogic != null); Guid dataModelDataElementGuid = Guid.Parse(instance.Data.Find(element => element.DataType.Equals(dataModelDataElement.Id))?.Id); Stream dataStream = await _dataService.GetBinaryData(org, app, instanceOwnerId, instanceGuid, dataModelDataElementGuid); byte[] dataAsBytes = new byte[dataStream.Length]; await dataStream.ReadAsync(dataAsBytes); string encodedXml = System.Convert.ToBase64String(dataAsBytes); byte[] formLayout = _appResourcesService.GetAppResource(org, app, _appSettings.FormLayoutJSONFileName); byte[] textResources = _appResourcesService.GetText(org, app, "resource.nb.json"); string formLayoutString = GetUTF8String(formLayout); string textResourcesString = GetUTF8String(textResources); PDFContext pdfContext = new PDFContext { Data = encodedXml, FormLayout = JsonConvert.DeserializeObject(formLayoutString), TextResources = JsonConvert.DeserializeObject(textResourcesString), Party = await _registerService.GetParty(instanceOwnerId), Instance = instance }; Stream pdfContent; try { pdfContent = await GeneratePDF(pdfContext); } catch (Exception exception) { _logger.LogError($"Could not generate pdf for {instance.Id}, failed with message {exception.Message}"); return; } try { await StorePDF(pdfContent, instance); } catch (Exception exception) { _logger.LogError($"Could not store pdf for {instance.Id}, failed with message {exception.Message}"); return; } finally { pdfContent.Dispose(); } }
/// <summary> /// Returns the user context /// </summary> /// <param name="context">The HttpContext</param> /// <returns>The UserContext</returns> public async Task <UserContext> GetUserContext(HttpContext context) { UserContext userContext = new UserContext() { User = context.User }; foreach (Claim claim in context.User.Claims) { if (claim.Type.Equals(AltinnCoreClaimTypes.UserName)) { userContext.UserName = claim.Value; } if (claim.Type.Equals(AltinnCoreClaimTypes.UserId)) { userContext.UserId = Convert.ToInt32(claim.Value); } if (claim.Type.Equals(AltinnCoreClaimTypes.PartyID)) { userContext.PartyId = Convert.ToInt32(claim.Value); } if (claim.Type.Equals(AltinnCoreClaimTypes.AuthenticationLevel)) { userContext.AuthenticationLevel = Convert.ToInt32(claim.Value); } } userContext.UserParty = await _registerService.GetParty(userContext.PartyId); if (context.Request.Cookies["altinncorereportee"] != null) { userContext.ReporteeId = Convert.ToInt32(context.Request.Cookies["altinncorereportee"]); } else { userContext.ReporteeId = userContext.PartyId; } userContext.Reportee = await _registerService.GetParty(userContext.ReporteeId); return(userContext); }
/// <summary> /// Returns the user context /// </summary> /// <param name="context">The HttpContext</param> /// <returns>The UserContext</returns> public async Task <UserContext> GetUserContext(HttpContext context) { UserContext userContext = new UserContext() { User = context.User }; foreach (Claim claim in context.User.Claims) { if (claim.Type.Equals(AltinnCoreClaimTypes.UserName)) { userContext.UserName = claim.Value; } if (claim.Type.Equals(AltinnCoreClaimTypes.UserId)) { userContext.UserId = Convert.ToInt32(claim.Value); } if (claim.Type.Equals(AltinnCoreClaimTypes.PartyID)) { userContext.PartyId = Convert.ToInt32(claim.Value); } if (claim.Type.Equals(AltinnCoreClaimTypes.AuthenticationLevel)) { userContext.AuthenticationLevel = Convert.ToInt32(claim.Value); } } UserProfile userProfile = await _profileService.GetUserProfile(userContext.UserId); userContext.UserParty = await _registerService.GetParty(userProfile.PartyId); if (context.Request.Cookies[_settings.GetAltinnPartyCookieName] != null) { userContext.PartyId = Convert.ToInt32(context.Request.Cookies[_settings.GetAltinnPartyCookieName]); } userContext.Party = await _registerService.GetParty(userContext.PartyId); return(userContext); }
public async Task <UserProfile> GetUserProfile(int userId) { UserProfile user = null; string path = GetProfilePath(userId); if (File.Exists(path)) { string content = File.ReadAllText(path); user = (UserProfile)JsonConvert.DeserializeObject(content, typeof(UserProfile)); } user.Party = await _registerService.GetParty(user.PartyId); return(user); }
public async Task <IActionResult> Index(string org, string service, int reporteeId) { if (reporteeId == 0) { return(LocalRedirect($"/designer/{org}/{service}/ManualTesting/Users/")); } CheckAndUpdateWorkflowFile(org, service); RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, Guid.Empty); requestContext.UserContext = await _userHelper.CreateUserContextBasedOnReportee(HttpContext, reporteeId); requestContext.Reportee = requestContext.UserContext.Reportee; StartServiceModel startServiceModel = new StartServiceModel { ServiceID = org + "_" + service, ReporteeList = _authorization.GetReporteeList(requestContext.UserContext.UserId) .Select(x => new SelectListItem { Text = x.ReporteeNumber + " " + x.ReporteeName, Value = x.PartyID.ToString() }) .ToList(), PrefillList = _testdata.GetServicePrefill(requestContext.Reportee.PartyId, org, service) .Select(x => new SelectListItem { Text = x.PrefillKey + " " + x.LastChanged, Value = x.PrefillKey }) .ToList(), ReporteeID = requestContext.Reportee.PartyId, Org = org, Service = service, }; if (reporteeId != 0 && reporteeId != startServiceModel.ReporteeID && startServiceModel.ReporteeList.Any(r => r.Value.Equals(reporteeId.ToString()))) { startServiceModel.ReporteeID = reporteeId; requestContext.Reportee = await _register.GetParty(startServiceModel.ReporteeID); requestContext.UserContext.ReporteeId = reporteeId; requestContext.UserContext.Reportee = requestContext.Reportee; HttpContext.Response.Cookies.Append("altinncorereportee", startServiceModel.ReporteeID.ToString()); } List <ServiceInstance> formInstances = _testdata.GetFormInstances(requestContext.Reportee.PartyId, org, service); ViewBag.InstanceList = formInstances.OrderBy(r => r.LastChanged).ToList(); return(View(startServiceModel)); }
public IActionResult Index(string org, string service, int reporteeId) { RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, 0); requestContext.UserContext = _userHelper.GetUserContext(HttpContext); requestContext.Reportee = requestContext.UserContext.Reportee; var startServiceModel = new StartServiceModel { ServiceID = org + "_" + service, ReporteeList = _authorization.GetReporteeList(requestContext.UserContext.UserId) .Select(x => new SelectListItem { Text = x.ReporteeNumber + " " + x.ReporteeName, Value = x.PartyID.ToString() }) .ToList(), PrefillList = _testdata.GetServicePrefill(requestContext.Reportee.PartyId, org, service) .Select(x => new SelectListItem { Text = x.PrefillKey + " " + x.LastChanged, Value = x.PrefillKey }) .ToList(), ReporteeID = requestContext.Reportee.PartyId }; if (reporteeId != 0 && reporteeId != startServiceModel.ReporteeID && startServiceModel.ReporteeList.Any(r => r.Value.Equals(reporteeId.ToString()))) { startServiceModel.ReporteeID = reporteeId; requestContext.Reportee = _register.GetParty(startServiceModel.ReporteeID); requestContext.UserContext.ReporteeId = reporteeId; requestContext.UserContext.Reportee = requestContext.Reportee; HttpContext.Response.Cookies.Append("altinncorereportee", startServiceModel.ReporteeID.ToString()); } List <ServiceInstance> formInstances = _testdata.GetFormInstances(requestContext.Reportee.PartyId, org, service); ViewBag.InstanceList = formInstances.OrderBy(r => r.LastChanged).ToList(); return(View(startServiceModel)); }
private async Task GenerateAndStoreReceiptPDF(Instance instance, string taskId, DataElement dataElement, Type dataElementModelType) { string app = instance.AppId.Split("/")[1]; string org = instance.Org; int instanceOwnerId = int.Parse(instance.InstanceOwner.PartyId); Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); string layoutSetsString = _resourceService.GetLayoutSets(); LayoutSets layoutSets = null; LayoutSet layoutSet = null; if (!string.IsNullOrEmpty(layoutSetsString)) { layoutSets = JsonConvert.DeserializeObject <LayoutSets>(layoutSetsString); layoutSet = layoutSets.Sets.FirstOrDefault(t => t.DataType.Equals(dataElement.DataType) && t.Tasks.Contains(taskId)); } string layoutSettingsFileContent = layoutSet == null?_resourceService.GetLayoutSettingsString() : _resourceService.GetLayoutSettingsStringForSet(layoutSet.Id); LayoutSettings layoutSettings = null; if (!string.IsNullOrEmpty(layoutSettingsFileContent)) { layoutSettings = JsonConvert.DeserializeObject <LayoutSettings>(layoutSettingsFileContent); } object data = await _dataService.GetFormData(instanceGuid, dataElementModelType, org, app, instanceOwnerId, new Guid(dataElement.Id)); layoutSettings = await FormatPdf(layoutSettings, data); XmlSerializer serializer = new XmlSerializer(dataElementModelType); using MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, data); stream.Position = 0; byte[] dataAsBytes = new byte[stream.Length]; await stream.ReadAsync(dataAsBytes); string encodedXml = Convert.ToBase64String(dataAsBytes); string language = "nb"; Party actingParty = null; ClaimsPrincipal user = _httpContextAccessor.HttpContext.User; int?userId = user.GetUserIdAsInt(); if (userId != null) { UserProfile userProfile = await _profileService.GetUserProfile((int)userId); actingParty = userProfile.Party; if (!string.IsNullOrEmpty(userProfile.ProfileSettingPreference?.Language)) { language = userProfile.ProfileSettingPreference.Language; } } else { string orgNumber = user.GetOrgNumber().ToString(); actingParty = await _registerService.LookupParty(new PartyLookup { OrgNo = orgNumber }); } // If layoutset exists pick correct layotFiles string formLayoutsFileContent = layoutSet == null?_resourceService.GetLayouts() : _resourceService.GetLayoutsForSet(layoutSet.Id); TextResource textResource = await _textService.GetText(org, app, language); if (textResource == null && language != "nb") { // fallback to norwegian if texts does not exist textResource = await _textService.GetText(org, app, "nb"); } string textResourcesString = JsonConvert.SerializeObject(textResource); Dictionary <string, Dictionary <string, string> > optionsDictionary = await GetOptionsDictionary(formLayoutsFileContent); PDFContext pdfContext = new PDFContext { Data = encodedXml, FormLayouts = JsonConvert.DeserializeObject <Dictionary <string, object> >(formLayoutsFileContent), LayoutSettings = layoutSettings, TextResources = JsonConvert.DeserializeObject(textResourcesString), OptionsDictionary = optionsDictionary, Party = await _registerService.GetParty(instanceOwnerId), Instance = instance, UserParty = actingParty, Language = language }; Stream pdfContent = await _pdfService.GeneratePDF(pdfContext); await StorePDF(pdfContent, instance, textResource); pdfContent.Dispose(); }
/// <summary> /// Run events related to instantiation /// </summary> /// <remarks> /// For example custom prefill. /// </remarks> /// <param name="instance">Instance information</param> /// <param name="data">The data object created</param> public async Task DataCreation(Instance instance, object data) { ePOB_M model = (ePOB_M)data; if (model.PersonInformasjon == null) { model.PersonInformasjon = new Personalia(); } if (model.PersonInformasjon.person == null) { model.PersonInformasjon.person = new Person(); } if (model.PersonInformasjon.postadresse == null) { model.PersonInformasjon.postadresse = new Adresse(); } if (model.DeusRequest == null) { model.DeusRequest = new Deusrequest(); } if (model.PersonRelasjoner == null) { model.PersonRelasjoner = new Relasjoner(); } if (model.Samboerellerektefelle == null) { model.Samboerellerektefelle = new Samboerektefelle(); } if (model.PersonligOkonomi == null) { model.PersonligOkonomi = new OEkonomi(); } if (model.HelsePerson == null) { model.HelsePerson = new Helse(); } if (model.PersonRusmidler == null) { model.PersonRusmidler = new Rusmidler(); } if (model.Straff == null) { model.Straff = new Strafferettslig(); } if (model.StatsTilknytning == null) { model.StatsTilknytning = new Statstilknytning(); } if (model.SikkerhetsOpplysninger == null) { model.SikkerhetsOpplysninger = new Sikkerhetsopplysninger(); } Altinn.Platform.Register.Models.Party party = await _registerService.GetParty(Convert.ToInt32(instance.InstanceOwner.PartyId)); model.PersonInformasjon.person.personnavn.fulltnavn = party.Name; Addfodselsdato(model, model.PersonInformasjon.person.foedselsnummer); model.PersonInformasjon.bostedsadresse.land = "NOR"; model.PersonInformasjon.postadresse.land = "NOR"; model.PersonInformasjon.prefiksnr = "47"; model.PersonInformasjon.sivilstatus = "Ugift"; model.PersonInformasjon.hattandrepersonnummer = "Nei"; model.PersonInformasjon.hatttidligerenavn = "Nei"; model.PersonInformasjon.harandrestatsborgerskap = "Nei"; model.PersonInformasjon.hatttidligerestatsborgerskap = "Nei"; model.PersonInformasjon.ishatttidligerenavn = false; model.PersonRelasjoner.fodtannetlandmor = "Nei"; model.PersonRelasjoner.fodtannetlandfar = "Nei"; model.PersonInformasjon.harandreiddokumenter = "Nei"; model.PersonInformasjon.hattoppholdutland = "Nei"; model.PersonInformasjon.hattoppholdeu = "Nei"; model.Samboerellerektefelle.hattsamboerstatsborgerandreland = "Nei"; model.Samboerellerektefelle.hattoppholdutland = "Nei"; model.Samboerellerektefelle.hattoppholdeos = "Nei"; model.PersonligOkonomi.hattprivatelaan = "Nei"; model.PersonligOkonomi.hattmislighold = "Nei"; model.PersonligOkonomi.hattpengespill = "Nei"; model.PersonligOkonomi.harinvesteringer = "Nei"; model.PersonligOkonomi.harmottattpenger = "Nei"; model.PersonligOkonomi.harsentpenger = "Nei"; model.PersonligOkonomi.okonomiskesituasjon = "God"; model.HelsePerson.hattsykdom = "Nei"; model.HelsePerson.hattvurderingsevne = "Nei"; model.HelsePerson.hattlegemidler = "Nei"; model.PersonRusmidler.hattalkoholreaksjoner = "Nei"; model.PersonRusmidler.hattalkoholhendelser = "Nei"; model.PersonRusmidler.hattdoping = "Nei"; model.PersonRusmidler.hattbruktnarkotika = "Nei"; model.PersonRusmidler.hattbehandlingrus = "Nei"; model.PersonRusmidler.hattakan = "Nei"; model.Straff.hattlovbruddnorge = "Nei"; model.Straff.hattlovbruddutland = "Nei"; model.Straff.hattrefselse = "Nei"; model.StatsTilknytning.hattkontaktetteretning = "Nei"; model.StatsTilknytning.hatttjenestemilitaere = "Nei"; model.StatsTilknytning.harstudertutland = "Nei"; model.StatsTilknytning.hatttjenensterutland = "Nei"; model.SikkerhetsOpplysninger.harandreforhold = "Nei"; model.SikkerhetsOpplysninger.hattkontaktkriminalitet = "Nei"; model.SikkerhetsOpplysninger.hattKontaktterror = "Nei"; await Task.CompletedTask; }
private async Task <Party> LookupParty(Instance instanceTemplate) { InstanceOwner instanceOwner = instanceTemplate.InstanceOwner; Party party; if (instanceOwner.PartyId != null) { try { party = await _registerService.GetParty(int.Parse(instanceOwner.PartyId)); if (!string.IsNullOrEmpty(party.SSN)) { instanceOwner.PersonNumber = party.SSN; instanceOwner.OrganisationNumber = null; } else if (!string.IsNullOrEmpty(party.OrgNumber)) { instanceOwner.PersonNumber = null; instanceOwner.OrganisationNumber = party.OrgNumber; } } catch (Exception e) { _logger.LogWarning($"Failed to lookup party by partyId: {instanceOwner.PartyId}. The exception was: {e.Message}"); throw new ServiceException(HttpStatusCode.BadRequest, $"Failed to lookup party by partyId: {instanceOwner.PartyId}. The exception was: {e.Message}", e); } } else { string lookupNumber = "personNumber or organisationNumber"; string personOrOrganisationNumber = instanceOwner.PersonNumber ?? instanceOwner.OrganisationNumber; try { if (!string.IsNullOrEmpty(instanceOwner.PersonNumber)) { lookupNumber = "personNumber"; party = await _registerService.LookupParty(new PartyLookup { Ssn = instanceOwner.PersonNumber }); } else if (!string.IsNullOrEmpty(instanceOwner.OrganisationNumber)) { lookupNumber = "organisationNumber"; party = await _registerService.LookupParty(new PartyLookup { OrgNo = instanceOwner.OrganisationNumber }); } else { throw new ServiceException(HttpStatusCode.BadRequest, "Neither personNumber or organisationNumber has value in instanceOwner"); } instanceOwner.PartyId = party.PartyId.ToString(); } catch (Exception e) { _logger.LogWarning($"Failed to lookup party by {lookupNumber}: {personOrOrganisationNumber}. The exception was: {e}"); throw new ServiceException(HttpStatusCode.BadRequest, $"Failed to lookup party by {lookupNumber}: {personOrOrganisationNumber}. The exception was: {e.Message}", e); } } return(party); }
public async Task <IActionResult> Index(string org, string service, int reporteeId) { var developer = AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext); string apiUrl = _settings.GetRuntimeAPIPath("ZipAndSendRepo", org, service, developer); using (HttpClient client = AuthenticationHelper.GetDesignerHttpClient(_httpContextAccessor.HttpContext, _testdataRepositorySettings.GetDesignerHost())) { client.BaseAddress = new Uri(apiUrl); HttpResponseMessage response = await client.GetAsync(apiUrl); string zipPath = $"{_settings.GetServicePath(org, service, developer)}{service}.zip"; string extractPath = _settings.GetServicePath(org, service, developer); if (!Directory.Exists(extractPath)) { Directory.CreateDirectory(extractPath); } else { Directory.Delete(extractPath, true); Directory.CreateDirectory(extractPath); } using (Stream s = response.Content.ReadAsStreamAsync().Result) { using (var w = System.IO.File.OpenWrite(zipPath)) { s.CopyTo(w); } } ZipFile.ExtractToDirectory(zipPath, extractPath); } RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, 0); requestContext.UserContext = _userHelper.GetUserContext(HttpContext); requestContext.Reportee = requestContext.UserContext.Reportee; var startServiceModel = new StartServiceModel { ServiceID = org + "_" + service, ReporteeList = _authorization.GetReporteeList(requestContext.UserContext.UserId) .Select(x => new SelectListItem { Text = x.ReporteeNumber + " " + x.ReporteeName, Value = x.PartyID.ToString() }) .ToList(), PrefillList = _testdata.GetServicePrefill(requestContext.Reportee.PartyId, org, service) .Select(x => new SelectListItem { Text = x.PrefillKey + " " + x.LastChanged, Value = x.PrefillKey }) .ToList(), ReporteeID = requestContext.Reportee.PartyId, Org = org, Service = service, }; if (reporteeId != 0 && reporteeId != startServiceModel.ReporteeID && startServiceModel.ReporteeList.Any(r => r.Value.Equals(reporteeId.ToString()))) { startServiceModel.ReporteeID = reporteeId; requestContext.Reportee = _register.GetParty(startServiceModel.ReporteeID); requestContext.UserContext.ReporteeId = reporteeId; requestContext.UserContext.Reportee = requestContext.Reportee; HttpContext.Response.Cookies.Append("altinncorereportee", startServiceModel.ReporteeID.ToString()); } List <ServiceInstance> formInstances = _testdata.GetFormInstances(requestContext.Reportee.PartyId, org, service, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); ViewBag.InstanceList = formInstances.OrderBy(r => r.LastChanged).ToList(); return(View(startServiceModel)); }
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}")); } // use process controller to start process instanceTemplate.Process = null; 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 multipart 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 multipart 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; return(Created(url, instance)); }
/// <inheritdoc/> public async Task GenerateAndStoreReceiptPDF(Instance instance, DataElement dataElement) { string app = instance.AppId.Split("/")[1]; string org = instance.Org; int instanceOwnerId = int.Parse(instance.InstanceOwner.PartyId); Application application = _appResourcesService.GetApplication(); Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); Stream dataStream = await _dataService.GetBinaryData(org, app, instanceOwnerId, instanceGuid, new Guid(dataElement.Id)); byte[] dataAsBytes = new byte[dataStream.Length]; await dataStream.ReadAsync(dataAsBytes); string encodedXml = Convert.ToBase64String(dataAsBytes); UserContext userContext = await _userHelper.GetUserContext(_httpContextAccessor.HttpContext); UserProfile userProfile = await _profileService.GetUserProfile(userContext.UserId); byte[] formLayout = _appResourcesService.GetAppResource(org, app, _appSettings.FormLayoutJSONFileName); TextResource textResource = await _textService.GetText(org, app, userProfile.ProfileSettingPreference.Language); string formLayoutString = GetUTF8String(formLayout); string textResourcesString = JsonConvert.SerializeObject(textResource); PDFContext pdfContext = new PDFContext { Data = encodedXml, FormLayout = JsonConvert.DeserializeObject(formLayoutString), TextResources = JsonConvert.DeserializeObject(textResourcesString), Party = await _registerService.GetParty(instanceOwnerId), Instance = instance, UserProfile = userProfile, UserParty = userProfile.Party }; Stream pdfContent; try { pdfContent = await GeneratePDF(pdfContext); } catch (Exception exception) { _logger.LogError($"Could not generate pdf for {instance.Id}, failed with message {exception.Message}"); return; } try { await StorePDF(pdfContent, instance, textResource); } catch (Exception exception) { _logger.LogError($"Could not store pdf for {instance.Id}, failed with message {exception.Message}"); return; } finally { pdfContent.Dispose(); } }
public async Task <dynamic> InstantiateApp(StartServiceModel startServiceModel) { // Dependency Injection: Getting the Service Specific Implementation based on the service parameter data store // Will compile code and load DLL in to memory for AltinnCore bool startService = true; IServiceImplementation serviceImplementation = _execution.GetServiceImplementation(startServiceModel.Org, startServiceModel.Service, startService); // Get the service context containing metadata about the service ServiceContext serviceContext = _execution.GetServiceContext(startServiceModel.Org, startServiceModel.Service, startService); // Create and populate the RequestContext object and make it available for the service implementation so // service developer can implement logic based on information about the request and the user performing // the request RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, Guid.Empty); requestContext.UserContext = await _userHelper.GetUserContext(HttpContext); // Populate the reportee information requestContext.UserContext.Party = await _register.GetParty(startServiceModel.PartyId); requestContext.Party = requestContext.UserContext.Party; // Checks if the reportee is allowed to initiate the application Application application = _repository.GetApplication(startServiceModel.Org, startServiceModel.Service); if (application != null && !InstantiationHelper.IsPartyAllowedToInstantiate(requestContext.UserContext.Party, application.PartyTypesAllowed)) { return(new StatusCodeResult(403)); } // Create platform service and assign to service implementation making it possible for the service implementation // to use plattform services. Also make it available in ViewBag so it can be used from Views serviceImplementation.SetPlatformServices(_platformSI); // Assign the different context information to the service implementation making it possible for // the service developer to take use of this information serviceImplementation.SetContext(requestContext, serviceContext, null, ModelState); object serviceModel = null; if (!string.IsNullOrEmpty(startServiceModel.PrefillKey)) { _form.GetPrefill( startServiceModel.Org, startServiceModel.Service, serviceImplementation.GetServiceModelType(), startServiceModel.PartyId, startServiceModel.PrefillKey); } if (serviceModel == null) { // If the service model was not loaded from prefill. serviceModel = serviceImplementation.CreateNewServiceModel(); } // Assign service model to the implementation serviceImplementation.SetServiceModel(serviceModel); // Run Instansiation event await serviceImplementation.RunServiceEvent(ServiceEventType.Instantiation); // Run validate Instansiation event where await serviceImplementation.RunServiceEvent(ServiceEventType.ValidateInstantiation); // If ValidateInstansiation event has not added any errors the new form is saved and user is redirercted to the correct if (ModelState.IsValid) { if (serviceContext.WorkFlow.Any() && serviceContext.WorkFlow[0].StepType.Equals(StepType.Lookup)) { return(JsonConvert.SerializeObject( new { org = startServiceModel.Org, service = startServiceModel.Service })); } int instanceOwnerId = requestContext.UserContext.PartyId; // Create a new instance document Instance instance = await _instance.InstantiateInstance(startServiceModel, serviceModel, serviceImplementation); // Create and store the instance created event InstanceEvent instanceEvent = new InstanceEvent { AuthenticationLevel = requestContext.UserContext.AuthenticationLevel, EventType = InstanceEventType.Created.ToString(), InstanceId = instance.Id, InstanceOwnerId = instanceOwnerId.ToString(), UserId = requestContext.UserContext.UserId, WorkflowStep = instance.Process.CurrentTask }; await _event.SaveInstanceEvent(instanceEvent, startServiceModel.Org, startServiceModel.Service); Enum.TryParse <WorkflowStep>(instance.Process.CurrentTask, out WorkflowStep currentStep); return(JsonConvert.SerializeObject( new { instanceId = instance.Id, })); } startServiceModel.PartyList = _authorization.GetPartyList(requestContext.UserContext.UserId) .Select(x => new SelectListItem { Text = (x.PartyTypeName == PartyType.Person) ? x.SSN + " " + x.Name : x.OrgNumber + " " + x.Name, Value = x.PartyId.ToString(), }).ToList(); HttpContext.Response.Cookies.Append(_generalSettings.GetAltinnPartyCookieName, startServiceModel.PartyId.ToString()); return(JsonConvert.SerializeObject( new { redirectUrl = View(startServiceModel), })); }
public async Task <IActionResult> StartService(StartServiceModel startServiceModel) { // Dependency Injection: Getting the Service Specific Implementation based on the service parameter data store // Will compile code and load DLL in to memory for AltinnCore bool startService = true; IServiceImplementation serviceImplementation = _execution.GetServiceImplementation(startServiceModel.Org, startServiceModel.Service, startService); // Get the service context containing metadata about the service ServiceContext serviceContext = _execution.GetServiceContext(startServiceModel.Org, startServiceModel.Service, startService); // Create and populate the RequestContext object and make it available for the service implementation so // service developer can implement logic based on information about the request and the user performing // the request RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, 0); requestContext.UserContext = _userHelper.GetUserContext(HttpContext); // Populate the reportee information requestContext.UserContext.Reportee = _register.GetParty(startServiceModel.ReporteeID); requestContext.Reportee = requestContext.UserContext.Reportee; // Create platform service and assign to service implementation making it possible for the service implementation // to use plattform services. Also make it available in ViewBag so it can be used from Views PlatformServices platformServices = new PlatformServices(_authorization, _repository, _execution, startServiceModel.Org, startServiceModel.Service); serviceImplementation.SetPlatformServices(platformServices); ViewBag.PlatformServices = platformServices; // Assign the different context information to the service implementation making it possible for // the service developer to take use of this information serviceImplementation.SetContext(requestContext, ViewBag, serviceContext, null, ModelState); object serviceModel = null; if (!string.IsNullOrEmpty(startServiceModel.PrefillKey)) { _form.GetPrefill( startServiceModel.Org, startServiceModel.Service, serviceImplementation.GetServiceModelType(), startServiceModel.ReporteeID, startServiceModel.PrefillKey); } if (serviceModel == null) { // If the service model was not loaded from prefill. serviceModel = serviceImplementation.CreateNewServiceModel(); } // Assign service model to the implementation serviceImplementation.SetServiceModel(serviceModel); // Run Instansiation event await serviceImplementation.RunServiceEvent(ServiceEventType.Instantiation); // Run validate Instansiation event where await serviceImplementation.RunServiceEvent(ServiceEventType.ValidateInstantiation); // If ValidateInstansiation event has not added any errors the new form is saved and user is redirercted to the correct if (ModelState.IsValid) { if (serviceContext.WorkFlow.Any() && serviceContext.WorkFlow[0].StepType.Equals(StepType.Lookup)) { return(RedirectToAction("Lookup", new { org = startServiceModel.Org, service = startServiceModel.Service })); } // Create a new instance Id int formID = _execution.GetNewServiceInstanceID(startServiceModel.Org, startServiceModel.Service); _form.SaveFormModel( serviceModel, formID, serviceImplementation.GetServiceModelType(), startServiceModel.Org, startServiceModel.Service, requestContext.UserContext.ReporteeId); ServiceState currentState = _workflowSI.InitializeService(formID, startServiceModel.Org, startServiceModel.Service, requestContext.UserContext.ReporteeId); string redirectUrl = _workflowSI.GetUrlForCurrentState(formID, startServiceModel.Org, startServiceModel.Service, currentState.State); return(Redirect(redirectUrl)); } startServiceModel.ReporteeList = _authorization.GetReporteeList(requestContext.UserContext.UserId) .Select(x => new SelectListItem { Text = x.ReporteeNumber + " " + x.ReporteeName, Value = x.PartyID.ToString(), }).ToList(); HttpContext.Response.Cookies.Append("altinncorereportee", startServiceModel.ReporteeID.ToString()); return(View(startServiceModel)); }
public async Task <IActionResult> Index(string org, string app, int partyId, int userId) { if (userId == 0 || partyId == 0) { return(LocalRedirect($"/designer/{org}/{app}/ManualTesting/Users/")); } bool?isValidSelection = await _authorization.ValidateSelectedParty(userId, partyId); if (isValidSelection != true) { return(LocalRedirect($"/designer/{org}/{app}/ManualTesting/Users/")); } Response.Cookies.Append( _generalSettings.GetAltinnPartyCookieName, partyId.ToString(), new CookieOptions { Domain = _generalSettings.HostName }); CheckAndUpdateWorkflowFile(org, app); RequestContext requestContext = RequestHelper.GetRequestContext(Request.Query, Guid.Empty); requestContext.UserContext = await _userHelper.CreateUserContextBasedOnUserAndParty(HttpContext, userId, partyId); requestContext.Party = requestContext.UserContext.Party; StartServiceModel startServiceModel = new StartServiceModel { ServiceID = org + "_" + app, PartyList = _authorization.GetPartyList(requestContext.UserContext.UserId) .Select(x => new SelectListItem { Text = (x.PartyTypeName == PartyType.Person) ? x.SSN + " " + x.Name : x.OrgNumber + " " + x.Name, Value = x.PartyId.ToString() }) .ToList(), PrefillList = _testdata.GetServicePrefill(requestContext.Party.PartyId, org, app) .Select(x => new SelectListItem { Text = x.PrefillKey + " " + x.LastChanged, Value = x.PrefillKey }) .ToList(), PartyId = requestContext.Party.PartyId, Org = org, Service = app, }; if (partyId != 0 && partyId != startServiceModel.PartyId && startServiceModel.PartyList.Any(r => r.Value.Equals(partyId.ToString()))) { startServiceModel.PartyId = partyId; requestContext.Party = await _register.GetParty(startServiceModel.PartyId); requestContext.UserContext.PartyId = partyId; requestContext.UserContext.Party = requestContext.Party; } List <ServiceInstance> formInstances = _testdata.GetFormInstances(requestContext.Party.PartyId, org, app); ViewBag.InstanceList = formInstances.OrderBy(r => r.LastChanged).ToList(); return(View(startServiceModel)); }
/// <inheritdoc/> public async Task PrefillDataModel(string partyId, string dataModelName, object dataModel) { string jsonConfig = _appResourcesService.GetPrefillJson(dataModelName); if (jsonConfig == null || jsonConfig == string.Empty) { return; } JObject prefillConfiguration = JObject.Parse(jsonConfig); JToken allowOverwriteToken = prefillConfiguration.SelectToken(ALLOW_OVERWRITE_KEY); if (allowOverwriteToken != null) { allowOverwrite = allowOverwriteToken.ToObject <bool>(); } Party party = await _registerService.GetParty(Int32.Parse(partyId)); if (party == null) { string errorMessage = $"Could find party for partyId: {partyId}"; _logger.LogError(errorMessage); throw new Exception(errorMessage); } // Prefill from user profile JToken profilePrefill = prefillConfiguration.SelectToken(USER_PROFILE_KEY); Dictionary <string, string> userProfileDict; if (profilePrefill != null) { userProfileDict = profilePrefill.ToObject <Dictionary <string, string> >(); if (userProfileDict.Count > 0) { int userId = AuthenticationHelper.GetUserId(_httpContextAccessor.HttpContext); UserProfile userProfile = await _profile.GetUserProfile(userId); if (userProfile != null) { JObject userProfileJsonObject = JObject.FromObject(userProfile); _logger.LogInformation($"Started prefill from {USER_PROFILE_KEY}"); LoopThroughDictionaryAndAssignValuesToDataModel(userProfileDict, userProfileJsonObject, dataModel); } else { string errorMessage = $"Could not prefill from {USER_PROFILE_KEY}, user profile is not defined."; _logger.LogError(errorMessage); } } } // Prefill from ER (enhetsregisteret) JToken enhetsregisteret = prefillConfiguration.SelectToken(ER_KEY); Dictionary <string, string> enhetsregisterPrefill; if (enhetsregisteret != null) { enhetsregisterPrefill = enhetsregisteret.ToObject <Dictionary <string, string> >(); if (enhetsregisterPrefill.Count > 0) { Organization org = party.Organization; if (org != null) { JObject orgJsonObject = JObject.FromObject(org); _logger.LogInformation($"Started prefill from {ER_KEY}"); LoopThroughDictionaryAndAssignValuesToDataModel(enhetsregisterPrefill, orgJsonObject, dataModel); } else { string errorMessage = $"Could not prefill from {ER_KEY}, organisation is not defined."; _logger.LogError(errorMessage); } } } // Prefill from DSF (det sentrale folkeregisteret) JToken folkeregisteret = prefillConfiguration.SelectToken(DSF_KEY); Dictionary <string, string> folkeregisterPrefill; if (folkeregisteret != null) { folkeregisterPrefill = folkeregisteret.ToObject <Dictionary <string, string> >(); if (folkeregisterPrefill.Count > 0) { Person person = party.Person; if (person != null) { JObject personJsonObject = JObject.FromObject(person); _logger.LogInformation($"Started prefill from {DSF_KEY}"); LoopThroughDictionaryAndAssignValuesToDataModel(folkeregisterPrefill, personJsonObject, dataModel); } else { string errorMessage = $"Could not prefill from {DSF_KEY}, person is not defined."; _logger.LogError(errorMessage); } } } }