private async Task <InstanceOwner> GetInstanceOwner(string partyValue, InstanceOwner owner)
        {
            Party party = null;

            if (partyValue.StartsWith(PartyPrefix))
            {
                owner.PartyId = partyValue.Replace(PartyPrefix, string.Empty);
                return(owner);
            }
            else if (partyValue.StartsWith(PersonPrefix))
            {
                string ssn = partyValue.Replace(PersonPrefix, string.Empty);
                party = await _registerService.LookupParty(new PartyLookup { Ssn = ssn });

                owner.PartyId      = party.PartyId.ToString();
                owner.PersonNumber = ssn;
            }
            else if (partyValue.StartsWith(OrgPrefix))
            {
                string orgno = partyValue.Replace(OrgPrefix, string.Empty);
                party = await _registerService.LookupParty(new PartyLookup { OrgNo = orgno });

                owner.PartyId            = party.PartyId.ToString();
                owner.OrganisationNumber = orgno;
            }

            return(owner);
        }
        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();
        }
        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);
        }