Ejemplo n.º 1
0
        public async Task <IActionResult> GetDynamicsLegalEntity(string id)
        {
            ViewModels.AdoxioLegalEntity 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(Json(result));
        }
        public void IsLiquorFalseOneThird()
        {
            // setup a scenario where liquor is true.
            var x = new List <MicrosoftDynamicsCRMadoxioLicences>();

            x.Add(new MicrosoftDynamicsCRMadoxioLicences()
            {
                AdoxioLicenceType = new MicrosoftDynamicsCRMadoxioLicencetype()
                {
                    AdoxioCategory = (int?)ViewModels.ApplicationTypeCategory.Cannabis
                }
            }
                  );
            x.Add(new MicrosoftDynamicsCRMadoxioLicences()
            {
                AdoxioLicenceType = new MicrosoftDynamicsCRMadoxioLicencetype()
                {
                    AdoxioCategory = (int?)ViewModels.ApplicationTypeCategory.Liquor
                }
            }
                  );
            x.Add(new MicrosoftDynamicsCRMadoxioLicences()
            {
                AdoxioLicenceType = new MicrosoftDynamicsCRMadoxioLicencetype()
                {
                    AdoxioCategory = (int?)ViewModels.ApplicationTypeCategory.Cannabis
                }
            }
                  );
            bool result = DynamicsExtensions.IsMostlyLiquor(x);

            Assert.False(result);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> UpdateDynamicsAccount([FromBody] ViewModels.Account item, string id)
        {
            _logger.LogDebug(LoggingEvents.HttpPut, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            _logger.LogDebug(LoggingEvents.HttpPut, "Account parameter: " + JsonConvert.SerializeObject(item));
            _logger.LogDebug(LoggingEvents.HttpPut, "id parameter: " + id);

            if (id != item.id)
            {
                _logger.LogWarning(LoggingEvents.BadRequest, "Bad Request. Id doesn't match the account id.");
                return(BadRequest());
            }

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

            if (!DynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient))
            {
                _logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to the account.");
                return(NotFound());
            }

            MicrosoftDynamicsCRMaccount adoxioAccount = await _dynamicsClient.GetAccountById(accountId);

            if (adoxioAccount == null)
            {
                _logger.LogWarning(LoggingEvents.NotFound, "Account NOT found.");
                return(new NotFoundResult());
            }

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

            // copy values over from the data provided
            adoxioAccount.CopyValues(item);

            try
            {
                await _dynamicsClient.Accounts.UpdateAsync(accountId.ToString(), adoxioAccount);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating the account. ");
                throw new Exception("Error updating the account.");
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error updating the account.");
                throw new Exception("Error updating the account.");
            }

            var updatedAccount = adoxioAccount.ToViewModel();

            _logger.LogDebug(LoggingEvents.HttpPut, "updatedAccount: " +
                             JsonConvert.SerializeObject(updatedAccount, Formatting.Indented, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));

            return(new JsonResult(updatedAccount));
        }
        public void IsLiquorFalseNoRecord()
        {
            // setup a scenario where liquor is true.
            var  x      = new List <MicrosoftDynamicsCRMadoxioLicences>();
            bool result = DynamicsExtensions.IsMostlyLiquor(x);

            Assert.False(result);
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> GetAccount(string id)
        {
            _logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            _logger.LogDebug(LoggingEvents.HttpGet, "id: " + id);

            Boolean userAccessToAccount = false;

            ViewModels.Account result = null;

            // query the Dynamics system to get the account record.
            if (id != null)
            {
                // verify the currently logged in user has access to this account
                Guid accountId = new Guid(id);

                try
                {
                    userAccessToAccount = DynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError(LoggingEvents.Error, "Error while checking if current user has access to account.");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                }

                if (!userAccessToAccount)
                {
                    _logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to account.");
                    return(new NotFoundResult());
                }

                MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountById(accountId);

                if (account == null)
                {
                    _logger.LogWarning(LoggingEvents.NotFound, "Account NOT found.");
                    return(new NotFoundResult());
                }
                result = account.ToViewModel();
            }
            else
            {
                _logger.LogWarning(LoggingEvents.BadRequest, "Bad Request.");
                return(BadRequest());
            }

            _logger.LogDebug(LoggingEvents.HttpGet, "Account result: " +
                             JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));
            return(Json(result));
        }
        public async Task <IActionResult> UpdateContact([FromBody] ViewModels.Contact item, string id)
        {
            if (id != null && item.id != null && id != item.id)
            {
                return(BadRequest());
            }
            var accessGranted = false;

            // get the contact



            // Allow access if the current user is the contact - for scenarios such as a worker update.
            if (DynamicsExtensions.CurrentUserIsContact(id, _httpContextAccessor))
            {
                accessGranted = true;
            }
            else
            {
                var contact = await _dynamicsClient.GetContactById(id);

                // get the related account and determine if the current user is allowed access
                if (!string.IsNullOrEmpty(contact?._parentcustomeridValue))
                {
                    var accountId = Guid.Parse(contact._parentcustomeridValue);
                    accessGranted =
                        DynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor,
                                                                         _dynamicsClient);
                }
            }

            if (!accessGranted)
            {
                _logger.LogError(LoggingEvents.BadRequest, $"Current user has NO access to the contact record. Aborting update to contact {id} ");
                return(NotFound());
            }

            var patchContact = new MicrosoftDynamicsCRMcontact();

            patchContact.CopyValues(item);
            try
            {
                await _dynamicsClient.Contacts.UpdateAsync(id, patchContact);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating contact");
            }

            var result = await _dynamicsClient.GetContactById(id);

            return(new JsonResult(result.ToViewModel()));
        }
        public JsonResult GetPhsLinkForContactGuid(string contactId)
        {
            string phsLink = null;

            try
            {
                phsLink = DynamicsExtensions.GetPhsLink(contactId, _configuration);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting personal history link");
            }
            return(new JsonResult(phsLink));
        }
        public JsonResult GetCASLinkForContactGuid(string contactId)
        {
            string casLink = null;

            try
            {
                casLink = DynamicsExtensions.GetCASLink(contactId, _configuration);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting cannabis associate screening link");
                _logger.LogError("Details:");
                _logger.LogError(ex.Message);
            }
            return(new JsonResult(casLink));
        }
        //[RequiresPermission(Permission.Login, Permission.NewUserRegistration)]


        public virtual IActionResult UsersCurrentGet()
        {
            SiteMinderAuthOptions siteMinderAuthOptions = new SiteMinderAuthOptions();

            ViewModels.User user = new ViewModels.User();

            // determine if we are a new registrant.
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            user.id           = userSettings.UserId;
            user.contactid    = userSettings.ContactId;
            user.accountid    = userSettings.AccountId;
            user.businessname = userSettings.BusinessLegalName;
            user.name         = userSettings.UserDisplayName;
            user.UserType     = userSettings.UserType;

            if (userSettings.IsNewUserRegistration)
            {
                user.isNewUser = true;
                // get details from the headers.


                user.lastname  = DynamicsExtensions.GetLastName(user.name);
                user.firstname = DynamicsExtensions.GetFirstName(user.name);
                user.accountid = userSettings.AccountId;

                string siteminderBusinessGuid = _httpContextAccessor.HttpContext.Request.Headers[siteMinderAuthOptions.SiteMinderBusinessGuidKey];
                string siteminderUserGuid     = _httpContextAccessor.HttpContext.Request.Headers[siteMinderAuthOptions.SiteMinderUserGuidKey];

                user.contactid             = string.IsNullOrEmpty(siteminderUserGuid) ? userSettings.ContactId : siteminderUserGuid;
                user.accountid             = string.IsNullOrEmpty(siteminderBusinessGuid) ? userSettings.AccountId : siteminderBusinessGuid;
                user.isEligibilityRequired = true;
            }
            else
            {
                user.lastname              = userSettings.AuthenticatedUser.Surname;
                user.firstname             = userSettings.AuthenticatedUser.GivenName;
                user.email                 = userSettings.AuthenticatedUser.Email;
                user.isNewUser             = false;
                user.isEligibilityRequired = EligibilityController.IsEligibilityCheckRequired(user.accountid, _configuration, _dynamicsClient);
            }


            return(new JsonResult(user));
        }
        public async Task <IActionResult> CreateWorkerContact([FromBody] ViewModels.Contact item)
        {
            // get the current user.
            UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

            // first check to see that we have the correct inputs.
            var contactSiteminderGuid = userSettings.SiteMinderGuid;

            if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0)
            {
                _logger.LogDebug(LoggingEvents.Error, "No Contact Siteminder Guid exernal id");
                throw new Exception("Error. No ContactSiteminderGuid exernal id");
            }

            // get the contact record.
            MicrosoftDynamicsCRMcontact userContact = null;

            // see if the contact exists.
            try
            {
                userContact = _dynamicsClient.GetActiveContactByExternalId(contactSiteminderGuid);
                if (userContact != null)
                {
                    throw new Exception("Contact already Exists");
                }
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error getting contact by Siteminder Guid.");
                throw new HttpOperationException("Error getting contact by Siteminder Guid");
            }

            // create a new contact.
            var contact = new MicrosoftDynamicsCRMcontact();
            var worker  = new MicrosoftDynamicsCRMadoxioWorker
            {
                AdoxioFirstname  = item.firstname,
                AdoxioMiddlename = item.middlename,
                AdoxioLastname   = item.lastname,
                AdoxioIsmanual   = 0 // 0 for false - is a portal user.
            };


            contact.CopyValues(item);
            // set the type to Retail Worker.
            contact.Customertypecode = 845280000;

            if (userSettings.NewWorker != null)
            {
                // get additional information from the service card headers.
                contact.CopyContactUserSettings(userSettings.NewContact);
                worker.CopyValues(userSettings.NewWorker);
            }

            //Default the country to Canada
            if (string.IsNullOrEmpty(contact.Address1Country))
            {
                contact.Address1Country = "Canada";
            }
            if (string.IsNullOrEmpty(contact.Address2Country))
            {
                contact.Address2Country = "Canada";
            }


            contact.AdoxioExternalid = DynamicsExtensions.GetServiceCardID(contactSiteminderGuid);

            try
            {
                worker.AdoxioContactId = contact;

                worker = await _dynamicsClient.Workers.CreateAsync(worker);

                contact = await _dynamicsClient.GetContactById(Guid.Parse(worker._adoxioContactidValue));
                await CreateSharepointDynamicsLink(worker);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating contact");
                _logger.LogError(httpOperationException.Response.Content);

                //fail
                throw httpOperationException;
            }


            // if we have not yet authenticated, then this is the new record for the user.
            if (userSettings.IsNewUserRegistration)
            {
                userSettings.ContactId = contact.Contactid;

                // we can now authenticate.
                if (userSettings.AuthenticatedUser == null)
                {
                    var user = new User();
                    user.Active    = true;
                    user.ContactId = Guid.Parse(userSettings.ContactId);
                    user.UserType  = userSettings.UserType;
                    user.SmUserId  = userSettings.UserId;
                    userSettings.AuthenticatedUser = user;
                }

                userSettings.IsNewUserRegistration = false;

                var userSettingsString = JsonConvert.SerializeObject(userSettings);
                _logger.LogDebug("userSettingsString --> " + userSettingsString);

                // add the user to the session.
                _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
                _logger.LogDebug("user added to session. ");
            }
            else
            {
                _logger.LogDebug(LoggingEvents.Error, "Invalid user registration.");
                throw new Exception("Invalid user registration.");
            }

            return(new JsonResult(contact.ToViewModel()));
        }
        public async Task <IActionResult> CreateContact([FromBody] ViewModels.Contact item)
        {
            // get the current user.
            UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

            // first check to see that a contact exists.
            var contactSiteminderGuid = userSettings.SiteMinderGuid;

            if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0)
            {
                _logger.LogDebug(LoggingEvents.Error, "No Contact Siteminder Guid exernal id");
                throw new Exception("Error. No ContactSiteminderGuid exernal id");
            }

            // get the contact record.
            MicrosoftDynamicsCRMcontact userContact = null;

            // see if the contact exists.
            try
            {
                userContact = _dynamicsClient.GetActiveContactByExternalId(contactSiteminderGuid);
                if (userContact != null)
                {
                    throw new Exception("Contact already Exists");
                }
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error getting contact by Siteminder Guid.");
                throw new HttpOperationException("Error getting contact by Siteminder Guid");
            }

            // create a new contact.
            var contact = new MicrosoftDynamicsCRMcontact();

            contact.CopyValues(item);


            if (userSettings.IsNewUserRegistration)
            {
                // get additional information from the service card headers.
                contact.CopyHeaderValues(_httpContextAccessor);
            }

            contact.AdoxioExternalid = DynamicsExtensions.GetServiceCardID(contactSiteminderGuid);
            try
            {
                contact = await _dynamicsClient.Contacts.CreateAsync(contact);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error creating contact. ");
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Unknown error creating contact.");
            }

            // if we have not yet authenticated, then this is the new record for the user.
            if (userSettings.IsNewUserRegistration)
            {
                userSettings.ContactId = contact.Contactid;

                // we can now authenticate.
                if (userSettings.AuthenticatedUser == null)
                {
                    var user = new User();
                    user.Active    = true;
                    user.ContactId = Guid.Parse(userSettings.ContactId);
                    user.UserType  = userSettings.UserType;
                    user.SmUserId  = userSettings.UserId;
                    userSettings.AuthenticatedUser = user;
                }

                userSettings.IsNewUserRegistration = false;

                var userSettingsString = JsonConvert.SerializeObject(userSettings);
                _logger.LogDebug("userSettingsString --> " + userSettingsString);

                // add the user to the session.
                _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
                _logger.LogDebug("user added to session. ");
            }
            else
            {
                _logger.LogDebug(LoggingEvents.Error, "Invalid user registration.");
                throw new Exception("Invalid user registration.");
            }

            return(new JsonResult(contact.ToViewModel()));
        }
        public async Task <IActionResult> CreateWorkerContact([FromBody] ViewModels.Contact item)
        {
            // get UserSettings from the session
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            // first check to see that a contact exists.
            string contactSiteminderGuid = userSettings.SiteMinderGuid;

            if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0)
            {
                _logger.LogError(LoggingEvents.Error, "No Contact Siteminder Guid exernal id");
                throw new Exception("Error. No ContactSiteminderGuid exernal id");
            }

            // get the contact record.
            MicrosoftDynamicsCRMcontact userContact = null;

            // see if the contact exists.
            try
            {
                userContact = _dynamicsClient.GetContactByExternalId(contactSiteminderGuid);
                if (userContact != null)
                {
                    throw new Exception("Contact already Exists");
                }
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError(LoggingEvents.Error, "Error getting contact by Siteminder Guid.");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                throw new OdataerrorException("Error getting contact by Siteminder Guid");
            }

            // create a new contact.
            MicrosoftDynamicsCRMcontact      contact = new MicrosoftDynamicsCRMcontact();
            MicrosoftDynamicsCRMadoxioWorker worker  = new MicrosoftDynamicsCRMadoxioWorker()
            {
                AdoxioFirstname  = item.firstname,
                AdoxioMiddlename = item.middlename,
                AdoxioLastname   = item.lastname
            };

            contact.CopyValues(item);

            if (userSettings.IsNewUserRegistration && userSettings.NewWorker != null)
            {
                // get additional information from the service card headers.
                contact.CopyValues(userSettings.NewContact);
                worker.CopyValues(userSettings.NewWorker);
            }

            contact.AdoxioExternalid = DynamicsExtensions.GetServiceCardID(contactSiteminderGuid);

            try
            {
                worker.AdoxioContactId = contact;

                worker = await _dynamicsClient.Workers.CreateAsync(worker);

                contact = await _dynamicsClient.GetContactById(Guid.Parse(worker._adoxioContactidValue));
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error updating contact");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
            }


            // if we have not yet authenticated, then this is the new record for the user.
            if (userSettings.IsNewUserRegistration)
            {
                userSettings.ContactId = contact.Contactid.ToString();

                // we can now authenticate.
                if (userSettings.AuthenticatedUser == null)
                {
                    Models.User user = new Models.User();
                    user.Active    = true;
                    user.ContactId = Guid.Parse(userSettings.ContactId);
                    user.UserType  = userSettings.UserType;
                    user.SmUserId  = userSettings.UserId;
                    userSettings.AuthenticatedUser = user;
                }

                userSettings.IsNewUserRegistration = false;

                string userSettingsString = JsonConvert.SerializeObject(userSettings);
                _logger.LogDebug("userSettingsString --> " + userSettingsString);

                // add the user to the session.
                _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
                _logger.LogDebug("user added to session. ");
            }
            else
            {
                _logger.LogError(LoggingEvents.Error, "Invalid user registration.");
                throw new Exception("Invalid user registration.");
            }

            return(Json(contact.ToViewModel()));
        }
Ejemplo n.º 13
0
        public IActionResult GetDynamicsLegalEntitiesByPosition(string parentLegalEntityId, string positionType)
        {
            List <ViewModels.AdoxioLegalEntity> result = new List <AdoxioLegalEntity>();
            IEnumerable <MicrosoftDynamicsCRMadoxioLegalentity> legalEntities = null;
            String filter = null;

            // Stops injections
            try
            {
                new Guid(parentLegalEntityId);
            }
            catch
            {
                return(NotFound());
            }

            filter = "_adoxio_legalentityowned_value eq " + parentLegalEntityId;
            switch (positionType)
            {
            case "shareholders":
                filter += " and adoxio_isshareholder eq true";
                break;

            case "partners":
                filter += " and adoxio_ispartner eq true";
                break;

            case "directors-officers-management":
                filter += " and adoxio_isshareholder ne true and adoxio_ispartner ne true";
                break;

            case "director-officer-shareholder":
                filter += " and adoxio_isindividual eq 1";
                break;

            default:
                break;
            }

            try
            {
                _logger.LogError("Account filter = " + filter);
                legalEntities = _dynamicsClient.Legalentities.Get(filter: filter).Value;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                throw;
            }

            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            if (legalEntities != null)
            {
                foreach (var legalEntity in legalEntities)
                {
                    // Users can't access other users legal entities.
                    if (!DynamicsExtensions.CurrentUserHasAccessToAccount(new Guid(legalEntity._adoxioAccountValue), _httpContextAccessor, _dynamicsClient))
                    {
                        return(NotFound());
                    }
                    result.Add(legalEntity.ToViewModel());
                }
            }

            return(Json(result));
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> DeleteDynamicsAccount(string id)
        {
            _logger.LogInformation(LoggingEvents.HttpPost, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);

            // verify the currently logged in user has access to this account
            Guid accountId = new Guid(id);

            if (!DynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient))
            {
                _logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to the account.");
                return(new NotFoundResult());
            }

            // get the account
            MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountById(accountId);

            if (account == null)
            {
                _logger.LogWarning(LoggingEvents.NotFound, "Account NOT found.");
                return(new NotFoundResult());
            }

            // delete the associated LegalEntity
            string accountFilter = "_adoxio_account_value eq " + id.ToString();
            var    legalEntities = _dynamicsClient.Adoxiolegalentities.Get(filter: accountFilter).Value.ToList();

            legalEntities.ForEach(le =>
            {
                try
                {
                    _dynamicsClient.Adoxiolegalentities.Delete(le.AdoxioLegalentityid);
                    _logger.LogDebug(LoggingEvents.HttpDelete, "Legal Entity deleted: " + le.AdoxioLegalentityid);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError(LoggingEvents.Error, "Error deleting the Legal Entity: " + le.AdoxioLegalentityid);
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                    throw new OdataerrorException("Error deleting the Legal Entity: " + le.AdoxioLegalentityid);
                }
            });

            try
            {
                await _dynamicsClient.Accounts.DeleteAsync(accountId.ToString());

                _logger.LogDebug(LoggingEvents.HttpDelete, "Account deleted: " + accountId.ToString());
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError(LoggingEvents.Error, "Error deleting the account: " + accountId.ToString());
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                throw new OdataerrorException("Error deleting the account: " + accountId.ToString());
            }

            _logger.LogDebug(LoggingEvents.HttpDelete, "No content returned.");
            return(NoContent()); // 204
        }
Ejemplo n.º 15
0
        public IActionResult GetDynamicsLegalEntitiesByPosition(string parentLegalEntityId, string positionType)
        {
            List <ViewModels.LegalEntity> result = new List <LegalEntity>();
            IEnumerable <MicrosoftDynamicsCRMadoxioLegalentity> legalEntities = null;
            String filter = null;

            // Stops injections
            try
            {
                new Guid(parentLegalEntityId);
            }
            catch
            {
                return(NotFound());
            }

            filter = "_adoxio_legalentityowned_value eq " + parentLegalEntityId;
            switch (positionType)
            {
            case "shareholders":
            case "partners":
                filter += " and (adoxio_ispartner eq true or adoxio_isshareholder eq true)";
                break;

            case "key-personnel":
                filter += " and adoxio_iskeypersonnel eq true";
                break;

            case "directors-officers-management":
                filter += " and (adoxio_isdirector eq true or adoxio_isseniormanagement eq true or adoxio_isofficer eq true)";
                break;

            case "director-officer-shareholder":
                filter += " and adoxio_isindividual eq 1";
                break;

            default:
                filter += " and adoxio_isindividual eq 2";     //return nothing
                break;
            }

            try
            {
                _logger.LogDebug("Account filter = " + filter);
                legalEntities = _dynamicsClient.Legalentities.Get(filter: filter).Value;
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, $"Error while getting account legal entities. ");
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unexpected Exception while getting legal entities.");
            }


            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            if (legalEntities != null)
            {
                foreach (var legalEntity in legalEntities)
                {
                    // Users can't access other users legal entities.
                    if (!DynamicsExtensions.CurrentUserHasAccessToAccount(new Guid(legalEntity._adoxioAccountValue), _httpContextAccessor, _dynamicsClient))
                    {
                        return(NotFound());
                    }
                    result.Add(legalEntity.ToViewModel());
                }
            }

            return(new JsonResult(result));
        }