Exemplo n.º 1
0
        public async Task <IActionResult> GetApplicantDynamicsLegalEntity()
        {
            ViewModels.LegalEntity result = null;

            // get the current user.
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            // check that the session is setup correctly.
            userSettings.Validate();

            // query the Dynamics system to get the legal entity record.
            MicrosoftDynamicsCRMadoxioLegalentity legalEntity = null;

            _logger.LogDebug("Find legal entity for applicant = " + userSettings.AccountId.ToString());

            legalEntity = _dynamicsClient.GetAdoxioLegalentityByAccountId(Guid.Parse(userSettings.AccountId));

            if (legalEntity == null)
            {
                return(new NotFoundResult());
            }
            // fix the account.

            result = legalEntity.ToViewModel();

            if (result.account == null)
            {
                MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountById(Guid.Parse(userSettings.AccountId));

                result.account = account.ToViewModel();
            }

            return(new JsonResult(result));
        }
Exemplo n.º 2
0
        public static async Task <ViewModels.LegalEntity> CreateOrganizationalShareholder(HttpClient _client, ViewModels.User user, string accountLegalEntityId)
        {
            var request   = new HttpRequestMessage(HttpMethod.Post, "/api/legalentities/child-legal-entity");
            var vmAccount = new ViewModels.Account
            {
                id = user.accountid
            };
            var vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                legalentitytype     = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                firstname           = "Test",
                middlename          = "The",
                lastname            = "Orgshareholder",
                name                = "Test Orgshareholder",
                dateofbirth         = DateTime.Now,
                isShareholder       = true,
                isindividual        = false,
                account             = vmAccount,
                parentLegalEntityId = accountLegalEntityId
            };
            var jsonString = JsonConvert.SerializeObject(vmAdoxioLegalEntity);

            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            var response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            ViewModels.LegalEntity responseDirector = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);

            var responseViewModel = await GetLegalEntityRecord(_client, responseDirector.id, true);

            Assert.Equal(responseDirector.name, responseViewModel.name);
            return(responseViewModel);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> GetDynamicsLegalEntity(string id)
        {
            ViewModels.LegalEntity result = null;
            // query the Dynamics system to get the legal entity record.
            if (string.IsNullOrEmpty(id))
            {
                return(new NotFoundResult());
            }
            else
            {
                // get the current user.
                string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
                UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

                Guid adoxio_legalentityid = new Guid(id);
                MicrosoftDynamicsCRMadoxioLegalentity adoxioLegalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid);

                //prevent getting legal entity data if the user is not associated with the account
                if (adoxioLegalEntity == null || !DynamicsExtensions.CurrentUserHasAccessToAccount(new Guid(adoxioLegalEntity._adoxioAccountValue), _httpContextAccessor, _dynamicsClient))
                {
                    return(new NotFoundResult());
                }
                result = adoxioLegalEntity.ToViewModel();
            }

            return(new JsonResult(result));
        }
        public async System.Threading.Tasks.Task UserCantAccessAnotherUsersShareholders()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var loginUser1    = randomNewUserName("NewSecUser1", 6);
            var businessName1 = randomNewUserName(loginUser1, 6);
            var strId1        = await LoginAndRegisterAsNewUser(loginUser1, businessName1);

            // verify the current user represents our new user
            ViewModels.User user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");

            // fetch our current account
            ViewModels.Account account1 = await GetAccountForCurrentUser();

            ViewModels.LegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client);

            Assert.Equal(user1.accountid, account1.id);

            // try to "hack" the query
            string hackId = legalEntity1.id + " or (adoxio_isshareholder eq true)";
            List <ViewModels.LegalEntity> doss = await SecurityHelper.GetLegalEntitiesByPosition(_client, hackId, "director-officer-shareholder", false);

            Assert.Null(doss);

            // logout and cleanup (deletes the account and contact created above ^^^)
            await LogoutAndCleanupTestUser(strId1);
            await GetCurrentUserIsUnauthorized();
        }
Exemplo n.º 5
0
        public static async Task <ViewModels.LegalEntity> GetLegalEntityRecordForCurrent(HttpClient _client)
        {
            var request  = new HttpRequestMessage(HttpMethod.Get, "/api/legalentities/applicant");
            var response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            var jsonString = await response.Content.ReadAsStringAsync();

            ViewModels.LegalEntity responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            return(responseViewModel);
        }
Exemplo n.º 6
0
        private List <ViewModels.LegalEntity> GetLegalEntityChildren(string parentLegalEntityId)
        {
            _logger.LogInformation(LoggingEvents.Get, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            _logger.LogDebug(LoggingEvents.Get, "parentLegalEntityId: {accouparentLegalEntityIdntId}");

            List <ViewModels.LegalEntity> children = null;
            var childEntitiesFilter = $"_adoxio_legalentityowned_value eq {parentLegalEntityId}";
            var expandList          = new List <string> {
                "adoxio_ShareholderAccountID", "adoxio_Account"
            };

            try
            {
                children = _dynamicsClient.Adoxiolegalentities
                           .Get(filter: childEntitiesFilter, expand: expandList).Value
                           .Select(le =>
                {
                    var legalEntity = le.ToViewModel();
                    var entity      = new ViewModels.LegalEntity
                    {
                        AdoxioLegalEntity = legalEntity,
                        Account           = le.AdoxioShareholderAccountID == null ? le.AdoxioAccount.ToViewModel() : le.AdoxioShareholderAccountID.ToViewModel()
                    };
                    var tiedHouse = _dynamicsClient.AdoxioTiedhouseconnections
                                    .Get(filter: $"_adoxio_accountid_value eq {entity.Account.id}")
                                    .Value.FirstOrDefault();
                    if (tiedHouse != null)
                    {
                        entity.TiedHouse = tiedHouse.ToViewModel();
                    }
                    if (entity.AdoxioLegalEntity.isShareholder == true && entity.AdoxioLegalEntity.isindividual == false)
                    {
                        entity.ChildEntities = GetLegalEntityChildren(entity.AdoxioLegalEntity.id);
                    }
                    return(entity);
                })
                           .ToList();
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError(LoggingEvents.Error, "Error getting legal entity children for parentLegalEntityId {parentLegalEntityId}.");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                return(null);
            }

            _logger.LogDebug(LoggingEvents.Get, "LegalEntityChildren: " +
                             JsonConvert.SerializeObject(children, Formatting.Indented, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));
            return(children);
        }
 /// <summary>
 /// Copy values from View Model to Dynamics legal entity
 /// </summary>
 /// <param name="to"></param>
 /// <param name="from"></param>
 public static void CopyValues(this MicrosoftDynamicsCRMadoxioLegalentity to, ViewModels.LegalEntity from)
 {
     to.AdoxioCommonnonvotingshares = from.commonnonvotingshares;
     to.AdoxioCommonvotingshares    = from.commonvotingshares;
     to.AdoxioDateofbirth           = from.dateofbirth;
     to.AdoxioFirstname             = from.firstname;
     to.AdoxioInterestpercentage    = from.interestpercentage;
     to.AdoxioIsindividual          = (from.isindividual != null && (bool)from.isindividual) ? 1 : 0;
     to.AdoxioLastname  = from.lastname;
     to.AdoxioIstrustee = from.IsTrustee;
     if (from.legalentitytype != null)
     {
         to.AdoxioLegalentitytype = (int?)from.legalentitytype;
     }
     if (from.partnerType != null)
     {
         to.AdoxioPartnertype = (int?)from.partnerType;
     }
     to.AdoxioMiddlename               = from.middlename;
     to.AdoxioName                     = from.name;
     to.AdoxioIspartner                = from.isPartner;
     to.AdoxioIsshareholder            = from.isShareholder;
     to.AdoxioIstrustee                = false;
     to.AdoxioIsdirector               = from.isDirector;
     to.AdoxioIsofficer                = from.isOfficer;
     to.AdoxioIsseniormanagement       = from.isSeniorManagement;
     to.AdoxioIsowner                  = from.isOwner;
     to.AdoxioIskeypersonnel           = from.isKeyPersonnel;
     to.AdoxioPreferrednonvotingshares = from.preferrednonvotingshares;
     to.AdoxioPreferredvotingshares    = from.preferredvotingshares;
     to.AdoxioSameasapplyingperson     = (from.sameasapplyingperson != null && (bool)from.sameasapplyingperson) ? 1 : 0;
     to.AdoxioEmail                    = from.email;
     to.AdoxioDateofappointment        = from.dateofappointment;
     to.AdoxioDateofsharesissued       = from.dateIssued;
     to.AdoxioJobtitle                 = from.jobTitle;
     to.AdoxioNumberofmembers          = from.NumberOfMembers;
     to.AdoxioAnnualmembershipfee      = from.AnnualMembershipFee;
     to.AdoxioTotalshares              = from.TotalShares;
     // Assigning the account this way throws exception:
     // System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
     //if (from.account.id != null)
     //{
     //    // fetch the account from Dynamics.
     //    var getAccountTask = _system.GetAccountById(null, Guid.Parse(from.account.id));
     //    getAccountTask.Wait();
     //    to.Adoxio_Account= getAccountTask.Result;
     //}
     to.AdoxioDateemailsent = from.securityAssessmentEmailSentOn;
 }
        //[Fact]
        public async System.Threading.Tasks.Task TestGetDynamicsLegalEntitiesByPosition()
        {
            var loginUser = randomNewUserName("LegalEntityByPosTest", 6);
            var strId     = await LoginAndRegisterAsNewUser(loginUser, "LegalEntityByPosTest", "PrivateCorporation");

            // Creating parent
            var levelOneAccount = await AccountFactory();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"/api/{service}/business-profile-summary");
            var response = await _client.SendAsync(request);

            String jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            var responseViewModelList = JsonConvert.DeserializeObject <List <ViewModels.LegalEntity> >(jsonString);

            Assert.Equal("LegalEntityByPosTest TestBusiness", responseViewModelList.First().name);
            var levelOneLegalEntityId = responseViewModelList.First().id;

            // Creating child
            ViewModels.LegalEntity vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                legalentitytype    = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                name               = "Cannabis Test Investor",
                commonvotingshares = 100,
                account            = levelOneAccount,
                isShareholder      = true,
                isindividual       = false,
                // Parent's id must be populated
                parentLegalEntityId = levelOneLegalEntityId
            };

            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request         = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/child-legal-entity");
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            await _client.SendAsync(request);

            // Get legal entity by position
            request  = new HttpRequestMessage(HttpMethod.Get, $"/api/{service}/position/{levelOneLegalEntityId}/shareholders");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            await LogoutAndCleanupTestUser(strId);
        }
Exemplo n.º 9
0
        public static async Task <ViewModels.LegalEntity> GetLegalEntityRecord(HttpClient _client, string id, bool expectSuccess)
        {
            var request  = new HttpRequestMessage(HttpMethod.Get, "/api/legalentities/" + id);
            var response = await _client.SendAsync(request);

            if (expectSuccess)
            {
                response.EnsureSuccessStatusCode();
                var jsonString = await response.Content.ReadAsStringAsync();

                ViewModels.LegalEntity responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
                return(responseViewModel);
            }
            else
            {
                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
                var _discard = await response.Content.ReadAsStringAsync();

                return(null);
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> UpdateDynamicsLegalEntity([FromBody] ViewModels.LegalEntity item, string id)
        {
            if (id != item.id)
            {
                return(BadRequest());
            }

            // get the legal entity.
            Guid adoxio_legalentityid = new Guid(id);

            MicrosoftDynamicsCRMadoxioLegalentity adoxioLegalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid);

            if (adoxioLegalEntity == null)
            {
                return(new NotFoundResult());
            }

            // we are doing a patch, so wipe out the record.
            adoxioLegalEntity = new MicrosoftDynamicsCRMadoxioLegalentity();

            // copy values over from the data provided
            adoxioLegalEntity.CopyValues(item);
            try
            {
                _dynamicsClient.Legalentities.Update(adoxio_legalentityid.ToString(), adoxioLegalEntity);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, $"Error updating legal entity: {httpOperationException.Request.Content} Response: {httpOperationException.Response.Content}");
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unexpected Exception while updating legal entity");
            }


            adoxioLegalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid);

            return(new JsonResult(adoxioLegalEntity.ToViewModel()));
        }
Exemplo n.º 11
0
        public async System.Threading.Tasks.Task ParentCanAccessChild()
        {
            // register and login as our first user (parent)
            var loginUser1 = randomNewUserName("ParentCanAccessChildTest", 6);
            var strId1     = await LoginAndRegisterAsNewUser(loginUser1);

            var request  = new HttpRequestMessage(HttpMethod.Get, "/api/user/current");
            var response = await _client.SendAsync(request);

            string jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            ViewModels.User user1 = JsonConvert.DeserializeObject <ViewModels.User>(jsonString);

            var accountfilter = "_adoxio_account_value eq " + user1.accountid;
            var bpFilter      = "and (adoxio_isapplicant eq true or adoxio_isindividual eq 0)";
            var filter        = accountfilter + " " + bpFilter;

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/legalentities/business-profile-summary");
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            var parentLegalEntity   = JsonConvert.DeserializeObject <List <ViewModels.LegalEntity> >(jsonString).FirstOrDefault();
            var parentLegalEntityId = parentLegalEntity.id;

            // The Default development user should not be a new user.
            Assert.False(user1.isNewUser);
            Assert.NotNull(user1.accountid);
            Assert.NotEmpty(user1.accountid);

            ViewModels.Account account1 = await GetAccountForCurrentUser();

            Assert.NotNull(account1);

            // call the REST API to get the strId1
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/accounts/" + strId1);
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            ViewModels.Account retAccount1 = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);
            Assert.Equal(user1.accountid, retAccount1.id);

            var vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                legalentitytype    = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                name               = "Create ShareholderLE",
                commonvotingshares = 100,
                account            = account1,
                isShareholder      = true,
                isindividual       = false,
                // Setting parentLegalEntityId from viewmodel id
                parentLegalEntityId = parentLegalEntityId
            };

            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request         = new HttpRequestMessage(HttpMethod.Post, "/api/legalentities/child-legal-entity");
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            var responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            var childAccountId    = responseViewModel.accountId;

            response.EnsureSuccessStatusCode();

            ViewModels.Account account2 = await GetAccountForCurrentUser();

            Assert.NotNull(account2);

            // as our second user, view the account of the first user
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/accounts/" + childAccountId);
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            // logout
            await Logout();

            // cleanup both users
            await Login(loginUser1);
            await LogoutAndCleanupTestUser(strId1);
        }
        //[Fact]
        public async System.Threading.Tasks.Task TestCRUD()
        {
            string   changedName           = randomNewUserName("LETest ChangedName", 6);
            string   service               = "legalentities";
            string   firstName             = "LETFirst";
            string   middleName            = "LETMiddle";
            string   lastName              = "LETLast";
            string   initialName           = randomNewUserName(firstName + " " + lastName, 6);
            DateTime dateOfBirth           = DateTime.Now;
            int      commonNonVotingshares = 3000;
            int      commonVotingshares    = 2018;
            bool     isIndividual          = true;

            var loginUser = randomNewUserName("TestLegalEntityUser", 6);
            var strId     = await LoginAndRegisterAsNewUser(loginUser);

            // get the current account.

            var request  = new HttpRequestMessage(HttpMethod.Get, "/api/user/current");
            var response = await _client.SendAsync(request);

            string jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            ViewModels.User user = JsonConvert.DeserializeObject <ViewModels.User>(jsonString);

            string accountId = user.accountid;



            // C - Create
            request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service);

            ViewModels.Account vmAccount = new ViewModels.Account
            {
                id = accountId
            };

            ViewModels.LegalEntity vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                legalentitytype = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                //position = ViewModels.PositionOptions.Director,
                firstname             = firstName,
                middlename            = middleName,
                lastname              = lastName,
                name                  = initialName,
                dateofbirth           = dateOfBirth,
                isindividual          = isIndividual,
                commonvotingshares    = commonVotingshares,
                commonnonvotingshares = commonNonVotingshares,
                account               = vmAccount
            };

            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            try
            {
                response = await _client.SendAsync(request);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                throw;
            }
            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // parse as JSON.

            ViewModels.LegalEntity responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);

            // name should match.
            Assert.Equal(firstName + " " + lastName, responseViewModel.name);
            var newId = responseViewModel.id;

            // R - Read

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + newId);
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            Assert.Equal(firstName + " " + lastName, responseViewModel.name);

            // U - Update
            vmAdoxioLegalEntity.firstname = changedName;
            vmAdoxioLegalEntity.id        = responseViewModel.id;
            request = new HttpRequestMessage(HttpMethod.Put, "/api/" + service + "/" + newId)
            {
                Content = new StringContent(JsonConvert.SerializeObject(vmAdoxioLegalEntity), Encoding.UTF8, "application/json")
            };
            response = await _client.SendAsync(request);

            var _discard = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // verify that the update persisted.

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + newId);
            response = await _client.SendAsync(request);

            _discard = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            Assert.Equal(changedName, responseViewModel.firstname);

            // D - Delete

            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + newId + "/delete");
            response = await _client.SendAsync(request);

            _discard = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // second delete should return a 404.
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + newId + "/delete");
            response = await _client.SendAsync(request);

            _discard = await response.Content.ReadAsStringAsync();

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // should get a 404 if we try a get now.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + newId);
            response = await _client.SendAsync(request);

            _discard = await response.Content.ReadAsStringAsync();

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            await LogoutAndCleanupTestUser(strId);
        }
        //[Fact]
        public async System.Threading.Tasks.Task TestThreeTierShareholders()
        {
            string service = "legalentities";

            var loginUser = randomNewUserName("TestThreeTierShareholders", 6);
            var strId     = await LoginAndRegisterAsNewUser(loginUser, "Cybertron Commercial Goods", "PrivateCorporation");

            // Creating parent
            var levelOneAccount = await AccountFactory();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"/api/{service}/business-profile-summary");
            var response = await _client.SendAsync(request);

            String jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            var responseViewModelList = JsonConvert.DeserializeObject <List <ViewModels.LegalEntity> >(jsonString);

            Assert.Equal("Cybertron Commercial Goods TestBusiness", responseViewModelList.First().name);
            var levelOneLegalEntityId = responseViewModelList.First().id;

            // First tier director
            ViewModels.LegalEntity vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                firstname          = "Ms.",
                middlename         = "Test",
                lastname           = "Director",
                commonvotingshares = 100,
                account            = levelOneAccount,
                isDirector         = true,
                isindividual       = true,
                // Parent's id must be populated
                parentLegalEntityId = levelOneLegalEntityId
            };

            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request         = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/child-legal-entity");
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            jsonString = await response.Content.ReadAsStringAsync();

            var responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);

            Assert.Equal("Ms. Director", responseViewModel.name);

            // First tier officer
            vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                firstname          = "Andrew",
                middlename         = "Test",
                lastname           = "Officer",
                commonvotingshares = 100,
                account            = levelOneAccount,
                isOfficer          = true,
                isindividual       = true,
                // Parent's id must be populated
                parentLegalEntityId = levelOneLegalEntityId
            };

            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request         = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/child-legal-entity");
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            Assert.Equal("Andrew Officer", responseViewModel.name);

            // Creating child
            vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                legalentitytype    = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                name               = "Cannabis Test Investor",
                commonvotingshares = 100,
                account            = levelOneAccount,
                isShareholder      = true,
                isindividual       = false,
                // Parent's id must be populated
                parentLegalEntityId = levelOneLegalEntityId
            };

            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request         = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/child-legal-entity");
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            Assert.Equal("Cannabis Test Investor", responseViewModel.name);
            var levelTwoLegalEntityId = responseViewModel.id;
            var levelTwoAccountId     = responseViewModel.shareholderAccountId;
            var levelTwoAccount       = new ViewModels.Account {
                id = levelTwoAccountId
            };

            // Creating child 2
            vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                legalentitytype    = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                name               = "Green Group Investments",
                commonvotingshares = 100,
                account            = levelTwoAccount,
                isShareholder      = true,
                isindividual       = false,
                // Parent's id must be populated
                parentLegalEntityId = levelTwoLegalEntityId
            };

            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request         = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/child-legal-entity");
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            Assert.Equal("Green Group Investments", responseViewModel.name);
            var levelThreeLegalEntityId = responseViewModel.id;
            var levelThreeAccountId     = responseViewModel.shareholderAccountId;
            var levelThreeAccount       = new ViewModels.Account {
                id = levelThreeAccountId
            };

            // Second tier Officer
            vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                firstname          = "Carlos",
                middlename         = "Test",
                lastname           = "Officer",
                commonvotingshares = 100,
                account            = levelTwoAccount,
                isOfficer          = true,
                isindividual       = true,
                // Parent's id must be populated
                parentLegalEntityId = levelTwoLegalEntityId
            };

            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request         = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/child-legal-entity");
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            Assert.Equal("Carlos Officer", responseViewModel.name);

            // Third tier shareholder
            vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                firstname          = "Doug",
                middlename         = "Test",
                lastname           = "Baldwin",
                commonvotingshares = 100,
                account            = levelThreeAccount,
                isShareholder      = true,
                isindividual       = true,
                // Parent's id must be populated
                parentLegalEntityId = levelThreeLegalEntityId
            };

            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request         = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/child-legal-entity");
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            Assert.Equal("Doug Baldwin", responseViewModel.name);

            await LogoutAndCleanupTestUser(strId);
        }
        //[Fact]
        public async System.Threading.Tasks.Task TestFileListing()
        {
            string initialName = randomNewUserName("First InitialName", 6);
            string changedName = randomNewUserName("First ChangedName", 6);
            string service     = "legalentities";

            // Login as default user

            var loginUser = randomNewUserName("NewLoginUser", 6);
            var strId     = await LoginAndRegisterAsNewUser(loginUser);

            ViewModels.User user = await GetCurrentUser();

            // C - Create a Legal Entity

            var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service);

            ViewModels.LegalEntity viewmodel_adoxio_legalentity = new ViewModels.LegalEntity()
            {
                legalentitytype = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                isDirector      = true,
                name            = initialName
            };

            string jsonString = JsonConvert.SerializeObject(viewmodel_adoxio_legalentity);

            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            var response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            ViewModels.LegalEntity responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            // name should match.
            Assert.Equal(initialName, responseViewModel.name);
            string id = responseViewModel.id;

            // Attach a file

            string testData = "This is just a test.";

            byte[] bytes        = Encoding.ASCII.GetBytes(testData);
            string documentType = "Test Document Type";
            // Create random filename
            var chars       = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var stringChars = new char[9];
            var random      = new Random();

            for (int i = 0; i < stringChars.Length; i++)
            {
                stringChars[i] = chars[random.Next(chars.Length)];
            }
            var    randomString = new String(stringChars);
            string filename     = randomString + ".txt";

            MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----TestBoundary");
            var fileContent = new MultipartContent {
                new ByteArrayContent(bytes)
            };

            fileContent.Headers.ContentType                 = new MediaTypeHeaderValue("text/plain");
            fileContent.Headers.ContentDisposition          = new ContentDispositionHeaderValue("form-data");
            fileContent.Headers.ContentDisposition.Name     = "File";
            fileContent.Headers.ContentDisposition.FileName = filename;
            multiPartContent.Add(fileContent);
            multiPartContent.Add(new StringContent(documentType), "documentType");   // form input

            // create a new request object for the upload, as we will be using multipart form submission.
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/attachments");

            requestMessage.Content = multiPartContent;

            var uploadResponse = await _client.SendAsync(requestMessage);

            uploadResponse.EnsureSuccessStatusCode();

            // Verify that the file Meta Data matches
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            // Verify that the file can be downloaded and the contents match

            // Cleanup the Legal Entity

            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // should get a 404 if we try a get now.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            await LogoutAndCleanupTestUser(strId);
        }
        public async System.Threading.Tasks.Task TestCRUD()
        {
            string initialName = "InitialName";
            string changedName = "ChangedName";


            // register and login as our first user
            var loginUser1 = randomNewUserName("TestAccountUser", 6);

            await Login(loginUser1);

            // C - Create
            var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service);

            MicrosoftDynamicsCRMaccount account = new MicrosoftDynamicsCRMaccount()
            {
                Name             = initialName,
                AdoxioExternalid = Guid.NewGuid().ToString()
            };

            ViewModels.Account viewmodel_account = account.ToViewModel();

            viewmodel_account.businessType = "PublicCorporation";

            string jsonString = JsonConvert.SerializeObject(viewmodel_account);

            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            var response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            ViewModels.Account responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);

            // name should match.
            Assert.Equal(initialName, responseViewModel.name);
            Guid id = new Guid(responseViewModel.id);

            //String strid = responseViewModel.externalId;
            //Assert.Equal(strid, viewmodel_account.externalId);

            // R - Read

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);
            Assert.Equal(initialName, responseViewModel.name);

            account.Accountid = id.ToString();

            // get legal entity record for account
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/legalentities/applicant");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            ViewModels.LegalEntity legalentityViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            Assert.Equal(id.ToString(), legalentityViewModel.account.id);

            // U - Update
            account.Name = changedName;


            request = new HttpRequestMessage(HttpMethod.Put, "/api/" + service + "/" + id)
            {
                Content = new StringContent(JsonConvert.SerializeObject(account.ToViewModel()), Encoding.UTF8, "application/json")
            };
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // verify that the update persisted.

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);
            Assert.Equal(changedName, responseViewModel.name);

            // D - Delete

            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            string responseText = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // second delete should return a 404.
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // should get a 404 if we try a get now.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            await Logout();
        }
        //[Fact]
        public async System.Threading.Tasks.Task UserCantAccessAnotherUsersShareholders()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var loginUser1    = randomNewUserName("NewSecUser1", 6);
            var businessName1 = randomNewUserName(loginUser1, 6);
            var strId1        = await LoginAndRegisterAsNewUser(loginUser1, businessName1);

            // verify the current user represents our new user
            ViewModels.User user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");

            // fetch our current account
            ViewModels.Account account1 = await GetAccountForCurrentUser();

            ViewModels.LegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client);

            Assert.Equal(user1.accountid, account1.id);

            // *** create some shareholders and directors
            ViewModels.LegalEntity dos1 = await SecurityHelper.CreateDirectorOrShareholder(_client, user1, legalEntity1.id, true, false, false);

            Assert.NotNull(dos1);
            ViewModels.LegalEntity dos2 = await SecurityHelper.CreateDirectorOrShareholder(_client, user1, legalEntity1.id, false, true, false);

            Assert.NotNull(dos2);
            ViewModels.LegalEntity dos3 = await SecurityHelper.CreateDirectorOrShareholder(_client, user1, legalEntity1.id, false, false, true);

            Assert.NotNull(dos3);
            List <ViewModels.LegalEntity> dos1s = await SecurityHelper.GetLegalEntitiesByPosition(_client, legalEntity1.id, "director-officer-shareholder", true);

            Assert.NotNull(dos1s);
            Assert.Equal(3, dos1s.Count);
            // ***

            // logout and verify we are logged out
            await Logout();
            await GetCurrentUserIsUnauthorized();

            // register and login as a second user
            var loginUser2    = randomNewUserName("NewSecUser2", 6);
            var businessName2 = randomNewUserName(loginUser2, 6);
            var strId2        = await LoginAndRegisterAsNewUser(loginUser2, businessName2);

            ViewModels.User user2 = await GetCurrentUser();

            Assert.Equal(user2.name, loginUser2 + " TestUser");
            Assert.Equal(user2.businessname, businessName2 + " TestBusiness");
            ViewModels.Account account2 = await GetAccountForCurrentUser();

            Assert.NotEqual(account1.id, account2.id);
            Assert.Equal(user2.accountid, account2.id);

            // *** as user 2, try to access shareholders of account 1
            var tmp = await SecurityHelper.GetLegalEntityRecord(_client, dos1.id, false);

            Assert.Null(tmp);
            tmp = await SecurityHelper.GetLegalEntityRecord(_client, dos2.id, false);

            Assert.Null(tmp);
            tmp = await SecurityHelper.GetLegalEntityRecord(_client, dos3.id, false);

            Assert.Null(tmp);
            List <ViewModels.LegalEntity> dos2s = await SecurityHelper.GetLegalEntitiesByPosition(_client, legalEntity1.id, "director-officer-shareholder", false);

            Assert.Null(dos2s);
            // ***

            // logout and cleanup second test user
            await LogoutAndCleanupTestUser(strId2);
            await GetCurrentUserIsUnauthorized();

            // login again as the same user as above ^^^
            await Login(loginUser1, businessName1);

            user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");
            account1 = await GetAccountForCurrentUser();

            // *** cleanup shareholders records
            tmp = await SecurityHelper.GetLegalEntityRecord(_client, dos3.id, true);

            Assert.NotNull(tmp);
            await SecurityHelper.DeleteLegalEntityRecord(_client, dos3.id);

            tmp = await SecurityHelper.GetLegalEntityRecord(_client, dos2.id, true);

            Assert.NotNull(tmp);
            await SecurityHelper.DeleteLegalEntityRecord(_client, dos2.id);

            tmp = await SecurityHelper.GetLegalEntityRecord(_client, dos1.id, true);

            Assert.NotNull(tmp);
            await SecurityHelper.DeleteLegalEntityRecord(_client, dos1.id);

            // ***

            // logout and cleanup (deletes the account and contact created above ^^^)
            await LogoutAndCleanupTestUser(strId1);
            await GetCurrentUserIsUnauthorized();
        }
        //[Fact]
        public async System.Threading.Tasks.Task UserCantAccessAnotherUsersApplicationAttachments()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var loginUser1    = randomNewUserName("NewSecUser1", 6);
            var businessName1 = randomNewUserName(loginUser1, 6);
            var strId1        = await LoginAndRegisterAsNewUser(loginUser1, businessName1);

            // verify the current user represents our new user
            ViewModels.User user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");

            // fetch our current account
            ViewModels.Account account1 = await GetAccountForCurrentUser();

            ViewModels.LegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client);

            Assert.Equal(user1.accountid, account1.id);

            // *** create some license applications
            ViewModels.Application application1 = await SecurityHelper.CreateLicenceApplication(_client, account1);

            Assert.NotNull(application1);
            var tmp = await SecurityHelper.GetLicenceApplication(_client, application1.Id, true);

            Assert.NotNull(tmp);

            // add an attachment to the application
            string file1 = await SecurityHelper.UploadFileToApplication(_client, application1.Id, "TestAppFileSecurity");

            List <ViewModels.FileSystemItem> file1s = await SecurityHelper.GetFileListForApplication(_client, application1.Id, "TestAppFileSecurity", true);

            Assert.NotNull(file1s);
            Assert.Single(file1s);
            //string _data1 = await SecurityHelper.DownloadFileForApplication(_client, application1.id, file1s[0].id, true);
            // ***

            // logout and verify we are logged out
            await Logout();
            await GetCurrentUserIsUnauthorized();

            // register and login as a second user
            var loginUser2    = randomNewUserName("NewSecUser2", 6);
            var businessName2 = randomNewUserName(loginUser2, 6);
            var strId2        = await LoginAndRegisterAsNewUser(loginUser2, businessName2);

            ViewModels.User user2 = await GetCurrentUser();

            Assert.Equal(user2.name, loginUser2 + " TestUser");
            Assert.Equal(user2.businessname, businessName2 + " TestBusiness");
            ViewModels.Account account2 = await GetAccountForCurrentUser();

            Assert.NotEqual(account1.id, account2.id);
            Assert.Equal(user2.accountid, account2.id);

            // *** as user 2, try to access license applications of account 1
            tmp = await SecurityHelper.GetLicenceApplication(_client, application1.Id, false);

            Assert.Null(tmp);

            // test access to the application's attachment
            List <ViewModels.FileSystemItem> file2s = await SecurityHelper.GetFileListForApplication(_client, application1.Id, "TestFileSecurity", false);

            Assert.Null(file2s);
            //string _data2 = await SecurityHelper.DownloadFileForApplication(_client, application1.id, file1s[0].id, true);
            // ***

            // logout and cleanup second test user
            await LogoutAndCleanupTestUser(strId2);
            await GetCurrentUserIsUnauthorized();

            // login again as the same user as above ^^^
            await Login(loginUser1, businessName1);

            user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");
            account1 = await GetAccountForCurrentUser();

            // *** delete license applications of account 1
            // delete the application's attachments
            //await SecurityHelper.DeleteFileForApplication(_client, application1.id, file1s[0].id);

            await SecurityHelper.DeleteLicenceApplication(_client, application1.Id);

            // ***

            // logout and cleanup (deletes the account and contact created above ^^^)
            await LogoutAndCleanupTestUser(strId1);
            await GetCurrentUserIsUnauthorized();
        }
        //[Fact]
        public async System.Threading.Tasks.Task UserCantAccessAnotherUsersChildBusinesProfileAttachments()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var loginUser1    = randomNewUserName("NewSecUser1", 6);
            var businessName1 = randomNewUserName(loginUser1, 6);
            var strId1        = await LoginAndRegisterAsNewUser(loginUser1, businessName1);

            // verify the current user represents our new user
            ViewModels.User user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");

            // fetch our current account
            ViewModels.Account account1 = await GetAccountForCurrentUser();

            ViewModels.LegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client);

            Assert.Equal(user1.accountid, account1.id);
            Assert.Equal(user1.accountid, legalEntity1.accountId);

            // *** create some org shareholders and child business profiles
            ViewModels.LegalEntity org1 = await SecurityHelper.CreateOrganizationalShareholder(_client, user1, legalEntity1.id);

            Assert.NotNull(org1);

            // upload some files under new org1
            ViewModels.Account org1Account = await SecurityHelper.GetAccountRecord(_client, org1.shareholderAccountId, true);

            Assert.NotNull(org1Account);

            string file1 = await SecurityHelper.UploadFileToLegalEntity(_client, org1.id, "TestFileSecurity");

            List <ViewModels.FileSystemItem> file1s = await SecurityHelper.GetFileListForAccount(_client, org1.shareholderAccountId, "TestFileSecurity", true);

            Assert.NotNull(file1s);
            Assert.Single(file1s);

            // TODO add a sub-profile of org1 profile as well, and add some attachments for it

            // ***

            // logout and verify we are logged out
            await Logout();
            await GetCurrentUserIsUnauthorized();

            // register and login as a second user
            var loginUser2    = randomNewUserName("NewSecUser2", 6);
            var businessName2 = randomNewUserName(loginUser2, 6);
            var strId2        = await LoginAndRegisterAsNewUser(loginUser2, businessName2);

            ViewModels.User user2 = await GetCurrentUser();

            Assert.Equal(user2.name, loginUser2 + " TestUser");
            Assert.Equal(user2.businessname, businessName2 + " TestBusiness");
            ViewModels.Account account2 = await GetAccountForCurrentUser();

            Assert.NotEqual(account1.id, account2.id);
            Assert.Equal(user2.accountid, account2.id);

            // *** as user 2, try to access child business profiles of account 1
            var tmp1 = await SecurityHelper.GetLegalEntityRecord(_client, org1.id, false);

            Assert.Null(tmp1);
            var tmp2 = await SecurityHelper.GetAccountRecord(_client, org1.shareholderAccountId, false);

            Assert.Null(tmp2);

            // try to access user1's files under new org1
            List <ViewModels.FileSystemItem> file2s = await SecurityHelper.GetFileListForAccount(_client, org1Account.id, "TestFileSecurity", false);

            Assert.Null(file2s);
            //string _data2 = await SecurityHelper.DownloadFileForAccount(_client, org1Account.id, file1s[0].id, true);

            // TODO test access to sub-profile of org1 profile's attachments as well

            // ***

            // logout and cleanup second test user
            await LogoutAndCleanupTestUser(strId2);
            await GetCurrentUserIsUnauthorized();

            // login again as the same user as above ^^^
            await Login(loginUser1, businessName1);

            user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");
            account1 = await GetAccountForCurrentUser();

            // *** cleanup business profile records
            tmp1 = await SecurityHelper.GetLegalEntityRecord(_client, org1.id, true);

            Assert.NotNull(tmp1);

            // ... and delete files under org1
            //await SecurityHelper.DeleteFileForAccount(_client, org1Account.id, file1s[0].id);

            await SecurityHelper.DeleteLegalEntityRecord(_client, org1.id);

            // ***

            // logout and cleanup (deletes the account and contact created above ^^^)
            await LogoutAndCleanupTestUser(strId1);
            await GetCurrentUserIsUnauthorized();
        }
        //[Fact]
        public async System.Threading.Tasks.Task UserCantAccessAnotherUsersBusinessProfiles()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var loginUser1    = randomNewUserName("NewSecUser1", 6);
            var businessName1 = randomNewUserName(loginUser1, 6);
            var strId1        = await LoginAndRegisterAsNewUser(loginUser1, businessName1);

            // verify the current user represents our new user
            ViewModels.User user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");

            // fetch our current account
            ViewModels.Account account1 = await GetAccountForCurrentUser();

            ViewModels.LegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client);

            Assert.Equal(user1.accountid, account1.id);

            // *** create some org shareholders and child business profiles
            ViewModels.LegalEntity org1 = await SecurityHelper.CreateOrganizationalShareholder(_client, user1, legalEntity1.id);

            Assert.NotNull(org1);

            // TODO create a sub-profile of org1 profile as well

            // ***

            // logout and verify we are logged out
            await Logout();
            await GetCurrentUserIsUnauthorized();

            // register and login as a second user
            var loginUser2    = randomNewUserName("NewSecUser2", 6);
            var businessName2 = randomNewUserName(loginUser2, 6);
            var strId2        = await LoginAndRegisterAsNewUser(loginUser2, businessName2);

            ViewModels.User user2 = await GetCurrentUser();

            Assert.Equal(user2.name, loginUser2 + " TestUser");
            Assert.Equal(user2.businessname, businessName2 + " TestBusiness");
            ViewModels.Account account2 = await GetAccountForCurrentUser();

            Assert.NotEqual(account1.id, account2.id);
            Assert.Equal(user2.accountid, account2.id);

            // *** as user 2, try to access child business profiles of account 1
            var tmp = await SecurityHelper.GetLegalEntityRecord(_client, org1.id, false);

            Assert.Null(tmp);

            // TODO test access to sub-profile of org1 profile as well

            // ***

            // logout and cleanup second test user
            await LogoutAndCleanupTestUser(strId2);
            await GetCurrentUserIsUnauthorized();

            // login again as the same user as above ^^^
            await Login(loginUser1, businessName1);

            user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");
            account1 = await GetAccountForCurrentUser();

            // *** cleanup business profile records
            tmp = await SecurityHelper.GetLegalEntityRecord(_client, org1.id, true);

            Assert.NotNull(tmp);

            // TODO clean up sub-profile of org1 profile as well

            await SecurityHelper.DeleteLegalEntityRecord(_client, org1.id);

            // ***

            // logout and cleanup (deletes the account and contact created above ^^^)
            await LogoutAndCleanupTestUser(strId1);
            await GetCurrentUserIsUnauthorized();
        }
        //[Fact]
        public async System.Threading.Tasks.Task UserCantAccessAnotherUsersAccount()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var loginUser1    = randomNewUserName("NewSecUser1", 6);
            var businessName1 = randomNewUserName(loginUser1, 6);
            var strId1        = await LoginAndRegisterAsNewUser(loginUser1, businessName1);

            // verify the current user represents our new user
            ViewModels.User user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");

            // fetch our current account
            ViewModels.Account account1 = await GetAccountForCurrentUser();

            ViewModels.LegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client);

            Assert.Equal(user1.accountid, account1.id);

            // logout and verify we are logged out
            await Logout();
            await GetCurrentUserIsUnauthorized();

            // register and login as a second user
            var loginUser2    = randomNewUserName("NewSecUser2", 6);
            var businessName2 = randomNewUserName(loginUser2, 6);
            var strId2        = await LoginAndRegisterAsNewUser(loginUser2, businessName2);

            ViewModels.User user2 = await GetCurrentUser();

            Assert.Equal(user2.name, loginUser2 + " TestUser");
            Assert.Equal(user2.businessname, businessName2 + " TestBusiness");
            ViewModels.Account account2 = await GetAccountForCurrentUser();

            Assert.NotEqual(account1.id, account2.id);
            Assert.Equal(user2.accountid, account2.id);

            // *** as user 2, try to access account and legal entity of account 1
            var secAccount = await SecurityHelper.GetAccountRecord(_client, account1.id, false);

            Assert.Null(secAccount);
            var secLegalEntity = await SecurityHelper.GetLegalEntityRecord(_client, legalEntity1.id, false);

            Assert.Null(secLegalEntity);

            secAccount = await SecurityHelper.UpdateAccountRecord(_client, account1.id, account1, false);

            Assert.Null(secAccount);
            // ***

            // logout and cleanup second test user
            await LogoutAndCleanupTestUser(strId2);
            await GetCurrentUserIsUnauthorized();

            // login again as the same user as above ^^^
            await Login(loginUser1, businessName1);

            user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");
            account1 = await GetAccountForCurrentUser();

            // logout and cleanup (deletes the account and contact created above ^^^)
            await LogoutAndCleanupTestUser(strId1);
            await GetCurrentUserIsUnauthorized();
        }
Exemplo n.º 21
0
        public IActionResult CreateDynamicsShareholderLegalEntity([FromBody] ViewModels.LegalEntity item)
        {
            if (item == null)
            {
                return(BadRequest());
            }

            MicrosoftDynamicsCRMadoxioLegalentity adoxioLegalEntity = new MicrosoftDynamicsCRMadoxioLegalentity();

            adoxioLegalEntity.CopyValues(item);

            if (item.isindividual != true)
            {
                var account = new MicrosoftDynamicsCRMaccount();
                account.Name = item.name;
                if (item.isShareholder == true)
                {
                    account.AdoxioAccounttype = (int)AdoxioAccountTypeCodes.Shareholder;
                }
                else if (item.isPartner == true)
                {
                    account.AdoxioAccounttype = (int)AdoxioAccountTypeCodes.Partner;
                }
                if (item.legalentitytype != null)
                {
                    account.AdoxioBusinesstype = (int)Enum.ToObject(typeof(Gov.Lclb.Cllb.Public.ViewModels.AdoxioApplicantTypeCodes), item.legalentitytype);
                }
                try
                {
                    account = _dynamicsClient.Accounts.Create(account);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, $"Error creating account: {httpOperationException.Request.Content} Response: {httpOperationException.Response.Content}");
                }
                catch (Exception e)
                {
                    _logger.LogError(e, $"Unexpected Exception while creating tied house connection");
                }

                //create tied house under account
                var tiedHouse = new MicrosoftDynamicsCRMadoxioTiedhouseconnection()
                {
                    AccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid)
                };

                adoxioLegalEntity.AdoxioShareholderAccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid);
                try
                {
                    _dynamicsClient.Tiedhouseconnections.Create(tiedHouse);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, $"Error creating tied house connection");
                }
                catch (Exception e)
                {
                    _logger.LogError(e, $"Unexpected Exception while creating tied house connection");
                }
            }
            adoxioLegalEntity.AdoxioAccountValueODataBind     = _dynamicsClient.GetEntityURI("accounts", item.account.id);
            adoxioLegalEntity.AdoxioLegalEntityOwnedODataBind = _dynamicsClient.GetEntityURI("adoxio_legalentities", item.parentLegalEntityId);

            try
            {
                adoxioLegalEntity = _dynamicsClient.Legalentities.Create(adoxioLegalEntity);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, $"Error creating legal entity: {httpOperationException.Request.Content} Response: {httpOperationException.Response.Content}");
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unexpected Exception while creating legal entity");
            }

            return(new JsonResult(adoxioLegalEntity.ToViewModel()));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Convert a Dynamics Legal Entity to a ViewModel
        /// </summary>
        public static ViewModels.LegalEntity ToViewModel(this MicrosoftDynamicsCRMadoxioLegalentity adoxio_legalentity)
        {
            ViewModels.LegalEntity result = null;
            if (adoxio_legalentity != null)
            {
                result = new ViewModels.LegalEntity();
                if (adoxio_legalentity.AdoxioLegalentityid != null)
                {
                    result.id = adoxio_legalentity.AdoxioLegalentityid.ToString();
                }

                if (adoxio_legalentity._adoxioAccountValue != null)
                {
                    result.accountId = adoxio_legalentity._adoxioAccountValue;
                }
                if (adoxio_legalentity._adoxioShareholderaccountidValue != null)
                {
                    result.shareholderAccountId = adoxio_legalentity._adoxioShareholderaccountidValue;
                }

                result.parentLegalEntityId = adoxio_legalentity._adoxioLegalentityownedValue;

                result.commonnonvotingshares = adoxio_legalentity.AdoxioCommonnonvotingshares;
                result.commonvotingshares    = adoxio_legalentity.AdoxioCommonvotingshares;
                result.dateofbirth           = adoxio_legalentity.AdoxioDateofbirth;
                result.firstname             = adoxio_legalentity.AdoxioFirstname;
                if (adoxio_legalentity.AdoxioInterestpercentage != null)
                {
                    result.interestpercentage = Convert.ToDecimal(adoxio_legalentity.AdoxioInterestpercentage);
                }

                // convert from int to bool.
                result.isindividual = (adoxio_legalentity.AdoxioIsindividual != null && adoxio_legalentity.AdoxioIsindividual != 0);
                result.lastname     = adoxio_legalentity.AdoxioLastname;
                if (adoxio_legalentity.AdoxioLegalentitytype != null)
                {
                    result.legalentitytype = (AdoxioApplicantTypeCodes)adoxio_legalentity.AdoxioLegalentitytype;
                }
                if (adoxio_legalentity.AdoxioPartnertype != null)
                {
                    result.partnerType = (AdoxioPartnerType)adoxio_legalentity.AdoxioPartnertype;
                }

                result.middlename    = adoxio_legalentity.AdoxioMiddlename;
                result.name          = adoxio_legalentity.AdoxioName;
                result.email         = adoxio_legalentity.AdoxioEmail;
                result.isPartner     = (adoxio_legalentity.AdoxioIspartner == true);
                result.isApplicant   = (adoxio_legalentity.AdoxioIsapplicant == true);
                result.isShareholder = (adoxio_legalentity.AdoxioIsshareholder == true);
                // result.isTrustee =  adoxio_legalentity.AdoxioIstrustee;
                result.isDirector         = (adoxio_legalentity.AdoxioIsdirector == true);
                result.isOfficer          = (adoxio_legalentity.AdoxioIsofficer == true);
                result.isSeniorManagement = (adoxio_legalentity.AdoxioIsseniormanagement == true);
                result.isOwner            = (adoxio_legalentity.AdoxioIsowner == true);
                result.isKeyPersonnel     = (adoxio_legalentity.AdoxioIskeypersonnel == true);

                result.preferrednonvotingshares = adoxio_legalentity.AdoxioPreferrednonvotingshares;
                result.preferredvotingshares    = adoxio_legalentity.AdoxioPreferredvotingshares;
                // convert from int to bool.
                result.sameasapplyingperson          = (adoxio_legalentity.AdoxioSameasapplyingperson != null && adoxio_legalentity.AdoxioSameasapplyingperson != 0);
                result.dateofappointment             = adoxio_legalentity.AdoxioDateofappointment;
                result.dateIssued                    = adoxio_legalentity.AdoxioDateofsharesissued;
                result.securityAssessmentEmailSentOn = adoxio_legalentity.AdoxioDateemailsent;
                result.jobTitle = adoxio_legalentity.AdoxioJobtitle;

                // populate the account.
                if (adoxio_legalentity.AdoxioAccount != null)
                {
                    result.account = adoxio_legalentity.AdoxioAccount.ToViewModel();
                }
            }
            return(result);
        }
Exemplo n.º 23
0
        public async Task <IActionResult> CreateDynamicsLegalEntity([FromBody] ViewModels.LegalEntity item)
        {
            // create a new legal entity.
            MicrosoftDynamicsCRMadoxioLegalentity adoxioLegalEntity = new MicrosoftDynamicsCRMadoxioLegalentity();

            // get the current user.
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            // check that the session is setup correctly.
            userSettings.Validate();
            // copy received values to Dynamics LegalEntity
            adoxioLegalEntity.CopyValues(item);
            try
            {
                adoxioLegalEntity = await _dynamicsClient.Legalentities.CreateAsync(adoxioLegalEntity);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, $"Error while creating legal entity ");
                throw new Exception("Unable to create legal entity");
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unexpected Exception while getting legal entities.");
                throw new Exception("Unable to create legal entity");
            }

            // setup navigation properties.
            MicrosoftDynamicsCRMadoxioLegalentity patchEntity = new MicrosoftDynamicsCRMadoxioLegalentity();
            Guid accountId   = Guid.Parse(userSettings.AccountId);
            var  userAccount = await _dynamicsClient.GetAccountById(accountId);

            patchEntity.AdoxioAccountValueODataBind = _dynamicsClient.GetEntityURI("accounts", accountId.ToString());

            // patch the record.
            try
            {
                await _dynamicsClient.Legalentities.UpdateAsync(adoxioLegalEntity.AdoxioLegalentityid, patchEntity);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, $"Error while patching legal entity: {httpOperationException.Request.Content} Response: {httpOperationException.Response.Content}");
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unexpected Exception while patching legal entity");
            }

            // TODO take the default for now from the parent account's legal entity record
            // TODO likely will have to re-visit for shareholders that are corporations/organizations
            MicrosoftDynamicsCRMadoxioLegalentity tempLegalEntity = _dynamicsClient.GetAdoxioLegalentityByAccountId(Guid.Parse(userSettings.AccountId));

            if (tempLegalEntity != null)
            {
                Guid tempLegalEntityId = Guid.Parse(tempLegalEntity.AdoxioLegalentityid);

                // see https://msdn.microsoft.com/en-us/library/mt607875.aspx
                patchEntity = new MicrosoftDynamicsCRMadoxioLegalentity();
                patchEntity.AdoxioLegalEntityOwnedODataBind = _dynamicsClient.GetEntityURI("adoxio_legalentities", tempLegalEntityId.ToString());

                // patch the record.
                try
                {
                    await _dynamicsClient.Legalentities.UpdateAsync(adoxioLegalEntity.AdoxioLegalentityid, patchEntity);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, $"Error adding LegalEntityOwned reference to legal entity: {httpOperationException.Request.Content} Response: {httpOperationException.Response.Content}");
                }
                catch (Exception e)
                {
                    _logger.LogError(e, $"Unexpected Exception while adding LegalEntityOwned reference to legal entity");
                }
            }

            return(new JsonResult(adoxioLegalEntity.ToViewModel()));
        }
        //[Fact]
        public async System.Threading.Tasks.Task TestAddShareholderAndDirector()
        {
            string service = "legalentities";

            var loginUser = randomNewUserName("TestAddSD", 6);
            var strId     = await LoginAndRegisterAsNewUser(loginUser);

            // get the current account.
            var request  = new HttpRequestMessage(HttpMethod.Get, "/api/user/current");
            var response = await _client.SendAsync(request);

            string jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            ViewModels.User user = JsonConvert.DeserializeObject <ViewModels.User>(jsonString);

            string accountId = user.accountid;

            // create a Shareholder and fetch it to verify
            request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service);
            ViewModels.Account vmAccount = new ViewModels.Account
            {
                id = user.accountid
            };
            ViewModels.LegalEntity vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                legalentitytype = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                //position = ViewModels.PositionOptions.Shareholder,
                firstname          = "Test",
                middlename         = "The",
                lastname           = "Shareholder",
                name               = "Test Shareholder",
                commonvotingshares = 100,
                isindividual       = true,
                account            = vmAccount
            };
            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            try
            {
                response = await _client.SendAsync(request);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                throw;
            }
            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            ViewModels.LegalEntity responseShareholder = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + responseShareholder.id);
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            var responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);

            Assert.Equal(responseShareholder.name, responseViewModel.name);

            // create a Director and fetch it to verify
            request   = new HttpRequestMessage(HttpMethod.Post, "/api/" + service);
            vmAccount = new ViewModels.Account
            {
                id = user.accountid
            };
            vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                legalentitytype = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                //position = ViewModels.PositionOptions.Director,
                firstname    = "Test",
                middlename   = "The",
                lastname     = "Director",
                name         = "Test Director",
                dateofbirth  = DateTime.Now,
                isindividual = true,
                account      = vmAccount
            };
            jsonString      = JsonConvert.SerializeObject(vmAdoxioLegalEntity);
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            try
            {
                response = await _client.SendAsync(request);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                throw;
            }
            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            ViewModels.LegalEntity responseDirector = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + responseDirector.id);
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            responseViewModel = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);
            Assert.Equal(responseDirector.name, responseViewModel.name);

            // logout
            await Logout();

            // login as new user and verify we can't see the Director or Shareholder
            var newLoginUser = randomNewUserName("TestAddSD2", 6);
            var newStrId     = await LoginAndRegisterAsNewUser(newLoginUser);

            // try to fetch LegalEntity records of other account
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + responseShareholder.id);
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            //response status code should be 404
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + responseDirector.id);
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            //response status code should be 404
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // logout
            await LogoutAndCleanupTestUser(newStrId);

            // log back in as user from above ^^^
            await Login(loginUser);

            // delete Director and Shareholder
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + responseDirector.id + "/delete");
            response = await _client.SendAsync(request);

            var _discard = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + responseShareholder.id + "/delete");
            response = await _client.SendAsync(request);

            _discard = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // logout and leanup account
            await LogoutAndCleanupTestUser(strId);
        }
        //[Fact]
        public async System.Threading.Tasks.Task UserCantAccessAnotherUsersInvoices()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var loginUser1    = randomNewUserName("NewSecUser1", 6);
            var businessName1 = randomNewUserName(loginUser1, 6);
            var strId1        = await LoginAndRegisterAsNewUser(loginUser1, businessName1);

            // verify the current user represents our new user
            ViewModels.User user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");

            // fetch our current account
            ViewModels.Account account1 = await GetAccountForCurrentUser();

            ViewModels.LegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client);

            Assert.Equal(user1.accountid, account1.id);

            // *** create some license applications and invoices
            ViewModels.Application application1 = await SecurityHelper.CreateLicenceApplication(_client, account1);

            Assert.NotNull(application1);
            var tmp = await SecurityHelper.GetLicenceApplication(_client, application1.Id, true);

            Assert.NotNull(tmp);

            // create invoices
            Dictionary <string, string> values = await SecurityHelper.PayLicenceApplicationFee(_client, application1.Id, false, true);

            Assert.NotNull(values);
            Assert.True(values.ContainsKey("trnApproved"));
            Assert.Equal("0", values["trnApproved"]);
            // ***

            // logout and verify we are logged out
            await Logout();
            await GetCurrentUserIsUnauthorized();

            // register and login as a second user
            var loginUser2    = randomNewUserName("NewSecUser2", 6);
            var businessName2 = randomNewUserName(loginUser2, 6);
            var strId2        = await LoginAndRegisterAsNewUser(loginUser2, businessName2);

            ViewModels.User user2 = await GetCurrentUser();

            Assert.Equal(user2.name, loginUser2 + " TestUser");
            Assert.Equal(user2.businessname, businessName2 + " TestBusiness");
            ViewModels.Account account2 = await GetAccountForCurrentUser();

            Assert.NotEqual(account1.id, account2.id);
            Assert.Equal(user2.accountid, account2.id);

            // *** as user 2, try to access license application invoices of account 1
            tmp = await SecurityHelper.GetLicenceApplication(_client, application1.Id, false);

            Assert.Null(tmp);

            // access invoices and try to pay
            values = await SecurityHelper.PayLicenceApplicationFee(_client, application1.Id, false, false);

            Assert.Null(values);
            // ***

            // logout and cleanup second test user
            await LogoutAndCleanupTestUser(strId2);
            await GetCurrentUserIsUnauthorized();

            // login again as the same user as above ^^^
            await Login(loginUser1, businessName1);

            user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");
            account1 = await GetAccountForCurrentUser();

            // TODO can't delete once invoices are created

            // logout and cleanup (deletes the account and contact created above ^^^)
            await Logout();
            await GetCurrentUserIsUnauthorized();
        }
Exemplo n.º 26
0
        public async Task <IActionResult> GetBusinessProfile(string accountId)
        {
            _logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            _logger.LogDebug(LoggingEvents.HttpGet, "accountId: {accountId}");

            List <LegalEntity> legalEntities;

            var expand = new List <string> {
                "primarycontactid"
            };
            var account = (_dynamicsClient.Accounts.Get(filter: "", expand: expand).Value.FirstOrDefault()).ToViewModel();

            _logger.LogDebug(LoggingEvents.HttpGet, "Account details: " + JsonConvert.SerializeObject(account));

            // get legal entities
            var entityFilter = $"_adoxio_account_value eq {accountId}";
            var expandList   = new List <string> {
                "adoxio_ShareholderAccountID"
            };

            try
            {
                legalEntities = _dynamicsClient.Adoxiolegalentities.Get(filter: entityFilter, expand: expandList).Value
                                .Select(le =>
                {
                    var legalEntity = le.ToViewModel();
                    var entity      = new ViewModels.LegalEntity
                    {
                        AdoxioLegalEntity = legalEntity,
                        Account           = le.AdoxioShareholderAccountID == null ? account : le.AdoxioShareholderAccountID.ToViewModel(),
                    };
                    entity.corporateDetailsFilesExists      = FileUploadExists(entity.Account.id, entity.Account.name, "Corporate Information").Result;
                    entity.organizationStructureFilesExists = FileUploadExists(entity.Account.id, entity.Account.name, "Organization Structure").Result;
                    entity.keyPersonnelFilesExists          = FileUploadExists(entity.Account.id, entity.Account.name, "Key Personnel").Result;
                    entity.financialInformationFilesExists  = FileUploadExists(entity.Account.id, entity.Account.name, "Financial Information").Result;
                    entity.shareholderFilesExists           = FileUploadExists(entity.Account.id, entity.Account.name, "Central Securities Register").Result;
                    var tiedHouse = _dynamicsClient.AdoxioTiedhouseconnections
                                    .Get(filter: $"_adoxio_accountid_value eq {entity.Account.id}")
                                    .Value.FirstOrDefault();
                    if (tiedHouse != null)
                    {
                        entity.TiedHouse = tiedHouse.ToViewModel();
                    }
                    entity.ChildEntities = GetLegalEntityChildren(entity.AdoxioLegalEntity.id);
                    return(entity);
                })
                                .ToList();
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError(LoggingEvents.Error, "Error getting legal entities for the account {accountId}.");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                return(null);
            }

            var profile = new BusinessProfile
            {
                Account       = account,
                LegalEntities = legalEntities
            };

            var isComplete = legalEntities.Select(le =>
            {
                var valid = new ProfileValidation
                {
                    LegalEntityId = le.AdoxioLegalEntity.id,
                    IsComplete    = (le.IsComplete())
                };
                return(valid);
            }).ToList();

            _logger.LogDebug(LoggingEvents.HttpGet, "BusinessProfile.isComplete: " +
                             JsonConvert.SerializeObject(isComplete, Formatting.Indented, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));
            return(Json(isComplete));
        }