Example #1
0
        private string GetApplicationFolderName(MicrosoftDynamicsCRMadoxioApplication application)
        {
            string applicationIdCleaned = application.AdoxioApplicationid.ToString().ToUpper().Replace("-", "");
            string folderName           = $"{application.AdoxioJobnumber}_{applicationIdCleaned}";

            return(folderName);
        }
        private async Task <MicrosoftDynamicsCRMadoxioApplication> GetDynamicsApplication(string id)
        {
            // get the current user.
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            _logger.LogDebug("Application id = " + id);
            _logger.LogDebug("User id = " + userSettings.AccountId);
            var expand = new List <string> {
                "adoxio_LicenceFeeInvoice", "adoxio_Invoice", "adoxio_Establishment"
            };

            MicrosoftDynamicsCRMadoxioApplication dynamicsApplication = await _dynamicsClient.GetApplicationByIdWithChildren(Guid.Parse(id));

            if (dynamicsApplication == null)
            {
                return(null);
            }
            else
            {
                if (!CurrentUserHasAccessToApplicationOwnedBy(dynamicsApplication._adoxioApplicantValue))
                {
                    return(null);
                }
            }

            return(dynamicsApplication);
        }
Example #3
0
        public static string GetDocumentFolderName(this MicrosoftDynamicsCRMadoxioApplication application)
        {
            string applicationIdCleaned = CleanGuidForSharePoint(application.AdoxioApplicationid);
            string folderName           = $"{application.AdoxioJobnumber}_{applicationIdCleaned}";

            return(folderName);
        }
Example #4
0
        public static void CopyValues(this MicrosoftDynamicsCRMadoxioApplication to, ViewModels.AdoxioApplication from)
        {
            to.AdoxioName = from.name;
            //to.Adoxio_jobnumber = from.jobNumber;
            to.AdoxioEstablishmentpropsedname       = from.establishmentName;
            to.AdoxioEstablishmentaddressstreet     = from.establishmentaddressstreet;
            to.AdoxioEstablishmentaddresscity       = from.establishmentaddresscity;
            to.AdoxioEstablishmentaddresspostalcode = from.establishmentaddresspostalcode;
            to.AdoxioAddresscity            = from.establishmentaddresscity;
            to.AdoxioEstablishmentparcelid  = from.establishmentparcelid;
            to.AdoxioContactpersonfirstname = from.contactpersonfirstname;
            to.AdoxioContactpersonlastname  = from.contactpersonlastname;
            to.AdoxioRole  = from.contactpersonrole;
            to.AdoxioEmail = from.contactpersonemail;
            to.AdoxioContactpersonphone            = from.contactpersonphone;
            to.AdoxioAuthorizedtosubmit            = from.authorizedtosubmit;
            to.AdoxioSignatureagreement            = from.signatureagreement;
            to.AdoxioAdditionalpropertyinformation = from.additionalpropertyinformation;


            to.AdoxioServicehoursstandardhours  = from.ServicehHoursStandardHours;
            to.AdoxioServicehourssundayopen     = (int?)from.ServiceHoursSundayOpen;
            to.AdoxioServicehourssundayclose    = (int?)from.ServiceHoursSundayClose;
            to.AdoxioServicehoursmondayopen     = (int?)from.ServiceHoursMondayOpen;
            to.AdoxioServicehoursmondayclose    = (int?)from.ServiceHoursMondayClose;
            to.AdoxioServicehourstuesdayopen    = (int?)from.ServiceHoursTuesdayOpen;
            to.AdoxioServicehourstuesdayclose   = (int?)from.ServiceHoursTuesdayClose;
            to.AdoxioServicehourswednesdayopen  = (int?)from.ServiceHoursWednesdayOpen;
            to.AdoxioServicehourswednesdayclose = (int?)from.ServiceHoursWednesdayClose;
            to.AdoxioServicehoursthursdayopen   = (int?)from.ServiceHoursThursdayOpen;
            to.AdoxioServicehoursthursdayclose  = (int?)from.ServiceHoursThursdayClose;
            to.AdoxioServicehoursfridayopen     = (int?)from.ServiceHoursFridayOpen;
            to.AdoxioServicehoursfridayclose    = (int?)from.ServiceHoursFridayClose;
            to.AdoxioServicehourssaturdayopen   = (int?)from.ServiceHoursSaturdayOpen;
            to.AdoxioServicehourssaturdayclose  = (int?)from.ServiceHoursSaturdayClose;
            to.AdoxioAuthorizedtosubmit         = from.AuthorizedToSubmit;
            to.AdoxioSignatureagreement         = from.SignatureAgreement;


            // comment out this next line as it is causing all application updates to fail (moved to controller)
            //to.AdoxioApplicanttype = (int)Enum.ToObject(typeof(Gov.Lclb.Cllb.Public.ViewModels.Adoxio_applicanttypecodes), from.applicantType);

            //if (from.adoxioInvoiceTrigger == GeneralYesNo.Yes)
            //{
            //	to.AdoxioInvoicetrigger = 1;
            //}

            //var adoxio_licencetype = dynamicsClient.GetAdoxioLicencetypeByName(from.licenseType).Result;
            //to.AdoxioLicenceType = adoxio_licencetype;
            //to._adoxioLicencetypeValue = adoxio_licencetype.AdoxioLicencetypeid;

            //if (!String.IsNullOrEmpty(from.applicationStatus))
            //{
            //    to.Statuscode = int.Parse(from.applicationStatus);
            //}
            //else
            //{
            //    to.Statecode = null;
            //}
        }
        public static void CopyValues(this MicrosoftDynamicsCRMadoxioApplication to, ViewModels.CovidApplication from)
        {
            to.AdoxioName = from.Name;
            //to.Adoxio_jobnumber = from.jobNumber;
            to.AdoxioEstablishmentpropsedname       = from.EstablishmentName;
            to.AdoxioEstablishmentaddressstreet     = from.EstablishmentAddressStreet;
            to.AdoxioEstablishmentaddresscity       = from.EstablishmentAddressCity;
            to.AdoxioEstablishmentaddresspostalcode = from.EstablishmentAddressPostalCode;
            // 12-10-2019 - Removed the update to AdoxioAddressCity as the Dynamics workflow handles that.

            to.AdoxioEstablishmentparcelid = from.EstablishmentParcelId;
            to.AdoxioEstablishmentphone    = from.EstablishmentPhone;
            to.AdoxioEstablishmentemail    = from.EstablishmentEmail;

            to.AdoxioContactpersonfirstname = from.ContactPersonFirstName;
            to.AdoxioContactpersonlastname  = from.ContactPersonLastName;
            to.AdoxioRole  = from.ContactPersonRole;
            to.AdoxioEmail = from.ContactPersonEmail;
            to.AdoxioContactpersonphone            = from.ContactPersonPhone;
            to.AdoxioAuthorizedtosubmit            = from.AuthorizedToSubmit;
            to.AdoxioAdditionalpropertyinformation = from.AdditionalPropertyInformation;

            to.AdoxioDescription1 = from.Description1;

            //store opening


            to.AdoxioAuthorizedtosubmit = from.AuthorizedToSubmit;

            to.AdoxioApplicanttype = (int?)from.ApplicantType;

            // catering fields
            to.AdoxioIsapplicationcomplete = (int?)from.IsApplicationComplete;
        }
        public static ApplicationSummary ToSummaryViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication)
        {
            ApplicationSummary applicationSummary = new ViewModels.ApplicationSummary()
            {
                Name      = dynamicsApplication.AdoxioName,
                JobNumber = dynamicsApplication.AdoxioJobnumber,
                //get establishment name and address
                EstablishmentName = dynamicsApplication.AdoxioEstablishmentpropsedname,
                LicenceId         = dynamicsApplication._adoxioAssignedlicenceValue,
                IsPaid            = (dynamicsApplication.AdoxioPaymentrecieved == true)
            };

            // id
            if (dynamicsApplication.AdoxioApplicationid != null)
            {
                applicationSummary.Id = dynamicsApplication.AdoxioApplicationid.ToString();
            }

            if (dynamicsApplication.Statuscode != null)
            {
                applicationSummary.ApplicationStatus = StatusUtility.GetTranslatedApplicationStatus(dynamicsApplication);
            }

            if (dynamicsApplication.AdoxioApplicationTypeId != null)
            {
                applicationSummary.ApplicationTypeName = dynamicsApplication.AdoxioApplicationTypeId.AdoxioName;
                applicationSummary.Portallabel         = dynamicsApplication.AdoxioApplicationTypeId.AdoxioPortallabel;
            }

            applicationSummary.IsIndigenousNation = (dynamicsApplication.AdoxioApplicanttype == (int)AdoxioApplicantTypeCodes.IndigenousNation);

            return(applicationSummary);
        }
Example #7
0
        private void UpdateEntityModifiedOnDate(string entityName, string entityId, bool setUploadedFromPortal = false)
        {
            switch (entityName.ToLower())
            {
            case "application":
                var patchApplication = new MicrosoftDynamicsCRMadoxioApplication();
                if (setUploadedFromPortal)
                {
                    patchApplication.AdoxioFileuploadedfromportal = (int?)ViewModels.GeneralYesNo.Yes;
                }

                try
                {
                    _dynamicsClient.Applications.Update(entityId, patchApplication);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, "Error updating application");
                    // fail if we can't create.
                    throw (httpOperationException);
                }
                break;

            case "contact":
                var patchContact = new MicrosoftDynamicsCRMcontact();
                try
                {
                    _dynamicsClient.Contacts.Update(entityId, patchContact);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, "Error updating Contact");
                    // fail if we can't create.
                    throw;
                }
                break;

            case "worker":
                var patchWorker = new MicrosoftDynamicsCRMadoxioWorker();
                try
                {
                    _dynamicsClient.Workers.Update(entityId, patchWorker);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, "Error updating Contact");
                    // fail if we can't create.
                    throw;
                }
                break;

            default:
                break;
            }
        }
        /// <summary>
        /// Get the licence type
        /// </summary>
        /// <param name="application"></param>
        /// <param name="dynamicsClient"></param>
        /// <param name="memoryCache"></param>
        public static void PopulateLicenceType(this MicrosoftDynamicsCRMadoxioApplication application, IDynamicsClient dynamicsClient, IMemoryCache memoryCache)
        {
            if (application._adoxioLicencetypeValue != null)
            {
                application.AdoxioLicenceType = GetCachedLicenceType(application._adoxioLicencetypeValue, dynamicsClient, memoryCache);
            }

            if (application.AdoxioAssignedLicence != null && application.AdoxioAssignedLicence._adoxioLicencetypeValue != null)
            {
                application.AdoxioAssignedLicence.AdoxioLicenceType = GetCachedLicenceType(application.AdoxioAssignedLicence._adoxioLicencetypeValue, dynamicsClient, memoryCache);
            }
        }
        public static ApplicationSummary ToSummaryViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication)
        {
            ApplicationSummary applicationSummary = new ViewModels.ApplicationSummary()
            {
                Name      = dynamicsApplication.AdoxioName,
                JobNumber = dynamicsApplication.AdoxioJobnumber,
                //get establishment name and address
                EstablishmentName              = dynamicsApplication.AdoxioEstablishmentpropsedname,
                LicenceId                      = dynamicsApplication._adoxioAssignedlicenceValue,
                IsPaid                         = (dynamicsApplication.AdoxioPaymentrecieved == true),
                EstablishmentAddressStreet     = dynamicsApplication.AdoxioEstablishmentaddressstreet,
                EstablishmentAddressCity       = dynamicsApplication.AdoxioEstablishmentaddresscity,
                EstablishmentAddressPostalCode = dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentAddress           = dynamicsApplication.AdoxioEstablishmentaddressstreet
                                                 + ", " + dynamicsApplication.AdoxioEstablishmentaddresscity
                                                 + " " + dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentPhone    = dynamicsApplication.AdoxioEstablishmentphone,
                EstablishmentEmail    = dynamicsApplication.AdoxioEstablishmentemail,
                EstablishmentParcelId = dynamicsApplication.AdoxioEstablishmentparcelid,
                IndigenousNationId    = dynamicsApplication._adoxioLocalgovindigenousnationidValue,
                PoliceJurisdictionId  = dynamicsApplication._adoxioPolicejurisdictionidValue,
                IsApplicationComplete = (GeneralYesNo?)dynamicsApplication.AdoxioIsapplicationcomplete
            };

            // id
            if (dynamicsApplication.AdoxioApplicationid != null)
            {
                applicationSummary.Id = dynamicsApplication.AdoxioApplicationid.ToString();
            }

            if (dynamicsApplication.Statuscode != null)
            {
                applicationSummary.ApplicationStatus = StatusUtility.GetTranslatedApplicationStatus(dynamicsApplication);
            }

            if (dynamicsApplication.AdoxioApplicationTypeId != null)
            {
                applicationSummary.ApplicationTypeName     = dynamicsApplication.AdoxioApplicationTypeId.AdoxioName;
                applicationSummary.IsForLicence            = dynamicsApplication.AdoxioApplicationTypeId._adoxioLicencetypeValue != null;
                applicationSummary.Portallabel             = dynamicsApplication.AdoxioApplicationTypeId.AdoxioPortallabel;
                applicationSummary.ApplicationTypeCategory = (ApplicationTypeCategory?)dynamicsApplication.AdoxioApplicationTypeId.AdoxioCategory;
            }

            applicationSummary.LGHasApproved = (dynamicsApplication.AdoxioLgapprovaldecision == (int?)LGDecision.Approved) ||
                                               (dynamicsApplication.AdoxioLgapprovaldecision == (int?)LGDecision.OptOut) ||
                                               (dynamicsApplication.AdoxioLgapprovaldecision == (int?)LGDecision.Pending) ||
                                               (dynamicsApplication.AdoxioLgzoning == (int?)Zoning.Allows);

            applicationSummary.IsIndigenousNation = (dynamicsApplication.AdoxioApplicanttype == (int)AdoxioApplicantTypeCodes.IndigenousNation);

            return(applicationSummary);
        }
Example #10
0
        public async Task <IActionResult> UpdateApplication([FromBody] ViewModels.Application item, string id)
        {
            if (id != item.Id)
            {
                return(BadRequest());
            }

            // for association with current user
            string       userJson     = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson);


            //Prepare application for update
            Guid adoxio_applicationId = new Guid(id);
            MicrosoftDynamicsCRMadoxioApplication adoxioApplication = await _dynamicsClient.GetApplicationById(adoxio_applicationId);

            if (!CurrentUserHasAccessToApplicationOwnedBy(adoxioApplication._adoxioApplicantValue))
            {
                return(new NotFoundResult());
            }

            adoxioApplication = new MicrosoftDynamicsCRMadoxioApplication();

            adoxioApplication.CopyValues(item);

            try
            {
                // Indigenous nation association
                if (!string.IsNullOrEmpty(item.IndigenousNationId))
                {
                    adoxioApplication.AdoxioLocalgovindigenousnationidODataBind = _dynamicsClient.GetEntityURI("adoxio_localgovindigenousnations", item.IndigenousNationId);
                }
                else
                {
                    //remove reference
                    await _dynamicsClient.Applications.DeleteReferenceAsync(item.Id, "adoxio_localgovindigenousnationid");
                }

                _dynamicsClient.Applications.Update(id, adoxioApplication);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating application");
                // fail if we can't create.
                throw (httpOperationException);
            }

            adoxioApplication = await _dynamicsClient.GetApplicationById(adoxio_applicationId);

            return(new JsonResult(await adoxioApplication.ToViewModel(_dynamicsClient)));
        }
Example #11
0
        private async Task <bool> CurrentUserIsLGForApplication(MicrosoftDynamicsCRMadoxioApplication application)
        {
            var temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            var userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            // get user account
            var accountId = GuidUtility.SanitizeGuidString(userSettings.AccountId);
            var account   = await _dynamicsClient.GetAccountByIdAsync(new Guid(accountId));

            // make sure the application and account have matching local government values
            var isLGForApplication = application != null && application._adoxioLocalgovindigenousnationidValue == account._adoxioLginlinkidValue;

            return(isLGForApplication);
        }
        private async Task <bool> CurrentUserIsLGForApplication(MicrosoftDynamicsCRMadoxioApplication application)
        {
            // get the current user.
            UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

            // get user account
            var accountId = GuidUtility.SanitizeGuidString(userSettings.AccountId);
            var account   = await _dynamicsClient.GetAccountByIdAsync(new Guid(accountId));

            // make sure the application and account have matching local government values
            var isLGForApplication = application != null && application._adoxioLocalgovindigenousnationidValue == account._adoxioLginlinkidValue;

            return(isLGForApplication);
        }
Example #13
0
        public async Task <IActionResult> CreateApplication([FromBody] ViewModels.AdoxioApplication item)
        {
            // for association with current user
            string       userJson     = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson);
            MicrosoftDynamicsCRMadoxioApplication adoxioApplication = new MicrosoftDynamicsCRMadoxioApplication();

            // copy received values to Dynamics Application
            adoxioApplication.CopyValues(item);
            adoxioApplication.AdoxioApplicanttype = (int?)item.applicantType;
            try
            {
                adoxioApplication = _dynamicsClient.Applications.Create(adoxioApplication);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error creating application");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                // fail if we can't create.
                throw (odee);
            }

            MicrosoftDynamicsCRMadoxioApplication patchAdoxioApplication = new MicrosoftDynamicsCRMadoxioApplication();

            // set license type relationship

            var adoxioLicencetype = _dynamicsClient.GetAdoxioLicencetypeByName(item.licenseType).Result;

            patchAdoxioApplication.AdoxioLicenceTypeODataBind = _dynamicsClient.GetEntityURI("adoxio_licencetypes", adoxioLicencetype.AdoxioLicencetypeid);;
            patchAdoxioApplication.AdoxioApplicantODataBind   = _dynamicsClient.GetEntityURI("adoxio_applications", userSettings.AccountId);
            try
            {
                _dynamicsClient.Applications.Update(adoxioApplication.AdoxioApplicationid, patchAdoxioApplication);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error updating application");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                // fail if we can't create.
                throw (odee);
            }
            return(Json(await adoxioApplication.ToViewModel(_dynamicsClient)));
        }
        public static void CopyValuesForChangeOfLocation(this MicrosoftDynamicsCRMadoxioApplication to, MicrosoftDynamicsCRMadoxioLicences from)
        {
            to.AdoxioEstablishmentpropsedname = from.AdoxioEstablishment.AdoxioName;

            /*
             * to.AdoxioAddresscity = from.AdoxioEstablishmentaddresscity;
             * to.AdoxioEstablishmentaddressstreet = from.AdoxioEstablishmentaddressstreet;
             * to.AdoxioEstablishmentaddresscity = from.AdoxioEstablishmentaddresscity;
             * to.AdoxioEstablishmentaddresspostalcode = from.AdoxioEstablishmentaddresspostalcode;
             * if (from.AdoxioEstablishment != null)
             * {
             *  to.AdoxioEstablishmentparcelid = from.AdoxioEstablishment.AdoxioParcelid;
             * }
             */
        }
        public static void CopyValuesForCovidApplication(this MicrosoftDynamicsCRMadoxioApplication to, ViewModels.CovidApplication from)
        {
            to.CopyValues(from);

            to.AdoxioProposedestablishmentisalr = from.ProposedEstablishmentIsAlr;

            to.AdoxioNameofapplicant = from.NameOfApplicant;

            /* 2020/5/15 - Copy values has a comment that says to not copy this fields because of a dynamics workflow
             * Including this fields for the covid application as the workflow should not be relevant ?
             */
            to.AdoxioAddressstreet     = from.AddressStreet;
            to.AdoxioAddresscity       = from.AddressCity;
            to.AdoxioAddresspostalcode = from.AddressPostalCode;
        }
Example #16
0
        public async Task <IActionResult> UpdateApplication([FromBody] ViewModels.AdoxioApplication item, string id)
        {
            if (id != item.id)
            {
                return(BadRequest());
            }

            // for association with current user
            string       userJson     = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson);


            //Prepare application for update
            Guid adoxio_applicationId = new Guid(id);
            MicrosoftDynamicsCRMadoxioApplication adoxioApplication = await _dynamicsClient.GetApplicationById(adoxio_applicationId);

            if (!CurrentUserHasAccessToApplicationOwnedBy(adoxioApplication._adoxioApplicantValue))
            {
                return(new NotFoundResult());
            }


            adoxioApplication = new MicrosoftDynamicsCRMadoxioApplication();

            adoxioApplication.CopyValues(item);

            try
            {
                _dynamicsClient.Applications.Update(id, adoxioApplication);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error updating application");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                // fail if we can't create.
                throw (odee);
            }

            adoxioApplication = await _dynamicsClient.GetApplicationById(adoxio_applicationId);

            return(Json(await adoxioApplication.ToViewModel(_dynamicsClient)));
        }
Example #17
0
        public async Task <IActionResult> CancelApplication(string id)
        {
            // get the application.
            Guid adoxio_applicationid = new Guid(id);

            MicrosoftDynamicsCRMadoxioApplication adoxioApplication = await _dynamicsClient.GetApplicationById(adoxio_applicationid);

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

            if (!CurrentUserHasAccessToApplicationOwnedBy(adoxioApplication._adoxioApplicantValue))
            {
                return(new NotFoundResult());
            }

            // set the status to Terminated.
            MicrosoftDynamicsCRMadoxioApplication patchRecord = new MicrosoftDynamicsCRMadoxioApplication()
            {
                //StatusCodeODataBind = ((int)AdoxioApplicationStatusCodes.Terminated).ToString()
                Statuscode = (int)AdoxioApplicationStatusCodes.Terminated
            };

            try
            {
                _dynamicsClient.Applications.Update(id, patchRecord);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error cancelling application");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                // fail if we can't create.
                throw (odee);
            }


            return(NoContent()); // 204
        }
Example #18
0
        public async Task <IActionResult> DeleteApplication(string id)
        {
            // get the application.
            Guid adoxio_applicationid = new Guid(id);

            MicrosoftDynamicsCRMadoxioApplication adoxioApplication = await _dynamicsClient.GetApplicationById(adoxio_applicationid);

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

            if (!CurrentUserHasAccessToApplicationOwnedBy(adoxioApplication._adoxioApplicantValue))
            {
                return(new NotFoundResult());
            }


            await _dynamicsClient.Applications.DeleteAsync(adoxio_applicationid.ToString());

            return(NoContent()); // 204
        }
        public static void CopyValuesForChangeOfLocation(this MicrosoftDynamicsCRMadoxioApplication to, MicrosoftDynamicsCRMadoxioLicences from, bool copyAddress)
        {
            // copy establishment information
            if (copyAddress)
            {
                // 12-10-2019 - Removed set to AdoxioAddressCity as it is set by Dynamics Workflow, not the portal
                to.AdoxioEstablishmentaddressstreet     = from.AdoxioEstablishmentaddressstreet;
                to.AdoxioEstablishmentaddresscity       = from.AdoxioEstablishmentaddresscity;
                to.AdoxioEstablishmentaddresspostalcode = from.AdoxioEstablishmentaddresspostalcode;
            }

            if (from.AdoxioEstablishment != null)
            {
                to.AdoxioEstablishmentpropsedname = from.AdoxioEstablishment.AdoxioName;
                to.AdoxioEstablishmentemail       = from.AdoxioEstablishment.AdoxioEmail;
                to.AdoxioEstablishmentphone       = from.AdoxioEstablishment.AdoxioPhone;
                to.AdoxioEstablishmentparcelid    = from.AdoxioEstablishment.AdoxioParcelid;
                to.AdoxioIsoninland                 = from.AdoxioEstablishment.AdoxioIsoninland;
                to.AdoxioPoliceJurisdictionId       = from.AdoxioEstablishment.AdoxioPDJurisdiction;
                to.AdoxioLocalgovindigenousnationid = from.AdoxioEstablishment.AdoxioLGIN;
            }
        }
        public void Move(DynamicsClient _dynamicsClient)
        {
            // first find Cantest1
            string filter = "name eq 'XYZ Cannabis Sales Test'";

            try
            {
                var cantest1 = _dynamicsClient.Accounts.Get(filter: filter).Value.FirstOrDefault();

                if (cantest1 != null)
                {
                    var applications = _dynamicsClient.Applications.Get().Value;

                    foreach (var application in applications)
                    {
                        try
                        {
                            MicrosoftDynamicsCRMadoxioApplication newItem = new MicrosoftDynamicsCRMadoxioApplication()
                            {
                                AdoxioApplicantODataBind = _dynamicsClient.GetEntityURI("accounts", cantest1.Accountid)
                            };
                            _dynamicsClient.Applications.Update(application.AdoxioApplicationid, newItem);
                        }
                        catch (OdataerrorException odee)
                        {
                            Console.Out.WriteLine("Error updating application");
                            Console.Out.WriteLine("Request:");
                            Console.Out.WriteLine(odee.Request.Content);
                            Console.Out.WriteLine("Response:");
                            Console.Out.WriteLine(odee.Response.Content);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("Unable to find Cantest1.");
            }
        }
        private async Task <MicrosoftDynamicsCRMadoxioApplication> GetDynamicsApplication(string id, bool getInvoice)
        {
            // get the current user.
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            _logger.LogError("Application id = " + id);
            _logger.LogError("User id = " + userSettings.AccountId);
            var expand = new List <string> {
                "adoxio_LicenceFeeInvoice", "adoxio_Invoice"
            };
            MicrosoftDynamicsCRMadoxioApplication dynamicsApplication = null;

            if (getInvoice)
            {
                dynamicsApplication = await _dynamicsClient.Applications.GetByKeyAsync(Guid.Parse(id).ToString(), expand : expand);
            }
            else
            {
                dynamicsApplication = await _dynamicsClient.Applications.GetByKeyAsync(Guid.Parse(id).ToString());
            }

            if (dynamicsApplication == null)
            {
                return(null);
            }
            else
            {
                if (!CurrentUserHasAccessToApplicationOwnedBy(dynamicsApplication._adoxioApplicantValue))
                {
                    return(null);
                }
            }

            return(dynamicsApplication);
        }
        public async static Task <ViewModels.Application> ToViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication, IDynamicsClient dynamicsClient, IMemoryCache cache, ILogger logger)
        {
            ViewModels.Application applicationVM = new ViewModels.Application()
            {
                Name      = dynamicsApplication.AdoxioName,
                JobNumber = dynamicsApplication.AdoxioJobnumber,
                //get establishment name and address
                EstablishmentName              = dynamicsApplication.AdoxioEstablishmentpropsedname,
                EstablishmentAddressStreet     = dynamicsApplication.AdoxioEstablishmentaddressstreet,
                EstablishmentAddressCity       = dynamicsApplication.AdoxioEstablishmentaddresscity,
                EstablishmentAddressPostalCode = dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentAddress           = dynamicsApplication.AdoxioEstablishmentaddressstreet
                                                 + ", " + dynamicsApplication.AdoxioEstablishmentaddresscity
                                                 + " " + dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentPhone    = dynamicsApplication.AdoxioEstablishmentphone,
                EstablishmentEmail    = dynamicsApplication.AdoxioEstablishmentemail,
                FederalProducerNames  = dynamicsApplication.AdoxioFederalproducernames,
                IsApplicationComplete = (GeneralYesNo?)dynamicsApplication.AdoxioIsapplicationcomplete,

                RenewalCriminalOffenceCheck     = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalcriminaloffencecheck,
                RenewalUnreportedSaleOfBusiness = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalunreportedsaleofbusiness,
                RenewalBusinessType             = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalbusinesstype,
                RenewalTiedhouse            = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaltiedhouse,
                RenewalOrgLeadership        = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalorgleadership,
                Renewalkeypersonnel         = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalkeypersonnel,
                RenewalShareholders         = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalshareholders,
                RenewalOutstandingFines     = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaloutstandingfines,
                RenewalBranding             = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalbranding,
                RenewalSignage              = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalsignage,
                RenewalEstablishmentAddress = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalestablishmentaddress,
                RenewalValidInterest        = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalvalidinterest,
                RenewalZoning            = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalzoning,
                RenewalFloorPlan         = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalfloorplan,
                RenewalSiteMap           = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalsitemap,
                TiedhouseFederalInterest = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaltiedhousefederalinterest,
                RenewalDUI        = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaldui,
                RenewalThirdParty = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalthirdparty,

                AuthorizedToSubmit = dynamicsApplication.AdoxioAuthorizedtosubmit,
                SignatureAgreement = dynamicsApplication.AdoxioSignatureagreement,

                LicenceFeeInvoicePaid = (dynamicsApplication.AdoxioLicencefeeinvoicepaid != null && dynamicsApplication.AdoxioLicencefeeinvoicepaid == true),

                // set a couple of read-only flags to indicate status
                IsPaid = (dynamicsApplication.AdoxioPaymentrecieved != null && (bool)dynamicsApplication.AdoxioPaymentrecieved),

                IndigenousNationId   = dynamicsApplication._adoxioLocalgovindigenousnationidValue,
                PoliceJurisdictionId = dynamicsApplication._adoxioPolicejurisdictionidValue,

                //get parcel id
                EstablishmentParcelId = dynamicsApplication.AdoxioEstablishmentparcelid,

                //get additional property info
                AdditionalPropertyInformation = dynamicsApplication.AdoxioAdditionalpropertyinformation,
                AdoxioInvoiceId = dynamicsApplication._adoxioInvoiceValue,

                PaymentReceivedDate = dynamicsApplication.AdoxioPaymentreceiveddate,
                Description1        = dynamicsApplication.AdoxioDescription1,
                Description2        = dynamicsApplication.AdoxioDescription2,

                //get contact details
                ContactPersonFirstName = dynamicsApplication.AdoxioContactpersonfirstname,
                ContactPersonLastName  = dynamicsApplication.AdoxioContactpersonlastname,
                ContactPersonRole      = dynamicsApplication.AdoxioRole,
                ContactPersonEmail     = dynamicsApplication.AdoxioEmail,
                ContactPersonPhone     = dynamicsApplication.AdoxioContactpersonphone,

                //get record audit info
                CreatedOn  = dynamicsApplication.Createdon,
                ModifiedOn = dynamicsApplication.Modifiedon,

                //store opening
                IsReadyWorkers                  = dynamicsApplication.AdoxioIsreadyworkers,
                IsReadyNameBranding             = dynamicsApplication.AdoxioIsreadynamebranding,
                IsReadyDisplays                 = dynamicsApplication.AdoxioIsreadydisplays,
                IsReadyIntruderAlarm            = dynamicsApplication.AdoxioIsreadyintruderalarm,
                IsReadyFireAlarm                = dynamicsApplication.AdoxioIsreadyfirealarm,
                IsReadyLockedCases              = dynamicsApplication.AdoxioIsreadylockedcases,
                IsReadyLockedStorage            = dynamicsApplication.AdoxioIsreadylockedstorage,
                IsReadyPerimeter                = dynamicsApplication.AdoxioIsreadyperimeter,
                IsReadyRetailArea               = dynamicsApplication.AdoxioIsreadyretailarea,
                IsReadyStorage                  = dynamicsApplication.AdoxioIsreadystorage,
                IsReadyExtranceExit             = dynamicsApplication.AdoxioIsreadyentranceexit,
                IsReadySurveillanceNotice       = dynamicsApplication.AdoxioIsreadysurveillancenotice,
                IsReadyProductNotVisibleOutside = dynamicsApplication.AdoxioIsreadyproductnotvisibleoutside,
                IsLocatedInGroceryStore         = dynamicsApplication.AdoxioIslocatedingrocerystore,
                Establishmentopeningdate        = dynamicsApplication.AdoxioEstablishmentopeningdate,
                IsReadyValidInterest            = dynamicsApplication.AdoxioIsreadyvalidinterest,

                IsHasPatio = dynamicsApplication.AdoxioIshaspatio,

                // LgInName
                LGNameOfOfficial         = dynamicsApplication.AdoxioLgnameofofficial,
                LGTitlePosition          = dynamicsApplication.AdoxioLgtitleposition,
                LGContactPhone           = dynamicsApplication.AdoxioLgcontactphone,
                LGContactEmail           = dynamicsApplication.AdoxioLgcontactemail,
                LGDecisionSubmissionDate = dynamicsApplication.AdoxioLgdecisionsubmissiondate,
                LgInName           = dynamicsApplication?.AdoxioLocalgovindigenousnationid?.AdoxioName,
                LGApprovalDecision = (LGDecision?)dynamicsApplication.AdoxioLgapprovaldecision,
                LgZoning           = (Zoning?)dynamicsApplication.AdoxioLgzoning,
                LGDecisionComments = dynamicsApplication.AdoxioLgdecisioncomments,

                // Catering fields.

                PreviousApplicationDetails = dynamicsApplication.AdoxioPreviouslicenceapplicationdetails,

                LiquorIndustryConnectionsDetails = dynamicsApplication.AdoxioLiquorindustryconnectionsdetails,

                OtherBusinessesDetails = dynamicsApplication.AdoxioOtherbusinesssamelocationdetails,
                ServiceAreas           = new List <CapacityArea>(),
                OutsideAreas           = new List <CapacityArea>(),
                CapacityArea           = new List <CapacityArea>(),

                // Manufacturing fields

                IsPackaging = dynamicsApplication.AdoxioIspackaging,

                MfgAcresOfFruit           = dynamicsApplication.AdoxioMfgacresoffruit,
                MfgAcresOfGrapes          = dynamicsApplication.AdoxioMfgacresofgrapes,
                MfgAcresOfHoney           = dynamicsApplication.AdoxioMfgacresofhoney,
                MfgMeetsProductionMinimum = dynamicsApplication.AdoxioMfgmeetsproductionminimum,
                MfgStepBlending           = dynamicsApplication.AdoxioMfgstepblending,
                MfgStepCrushing           = dynamicsApplication.AdoxioMfgstepcrushing,
                MfgStepFiltering          = dynamicsApplication.AdoxioMfgstepfiltering,
                MfgStepSecFermOrCarb      = dynamicsApplication.AdoxioMfgstepsecfermorcarb,
                IsOwnerBusiness           = dynamicsApplication.AdoxioIsownerbusiness,
                HasValidInterest          = dynamicsApplication.AdoxioIsownerhasvalidinterest,
                WillHaveValidInterest     = dynamicsApplication.AdoxioIsownerwillhavevalidinterest,
                ZoningStatus = dynamicsApplication.AdoxioZoningstatus,


                PidList             = dynamicsApplication.AdoxioPidlist,
                IsPermittedInZoning = dynamicsApplication.AdoxioIspermittedinzoning,

                // Manufacturing structural change fields

                PatioCompDescription          = dynamicsApplication.AdoxioPatiocompdescription,
                PatioLocationDescription      = dynamicsApplication.AdoxioPatiolocationdescription,
                PatioAccessDescription        = dynamicsApplication.AdoxioPatioaccessdescription,
                PatioIsLiquorCarried          = dynamicsApplication.AdoxioPatioisliquorcarried,
                PatioLiquorCarriedDescription = dynamicsApplication.AdoxioPatioliquorcarrieddescription,
                PatioAccessControlDescription = dynamicsApplication.AdoxioPatioaccesscontroldescription,
                IsAlr           = dynamicsApplication.AdoxioProposedestablishmentisalr.HasValue && (bool)dynamicsApplication.AdoxioProposedestablishmentisalr,
                HasCoolerAccess = dynamicsApplication.AdoxioHascooleraccess.HasValue && (bool)dynamicsApplication.AdoxioHascooleraccess
            };


            // mfg fields

            if (dynamicsApplication.AdoxioMfgpipedinproduct != null)
            {
                applicationVM.MfgPipedInProduct = (YesNoNotApplicable?)dynamicsApplication.AdoxioMfgpipedinproduct;
            }
            if (dynamicsApplication.AdoxioMfgbrewpubonsite != null)
            {
                applicationVM.MfgBrewPubOnSite = (YesNoNotApplicable?)dynamicsApplication.AdoxioMfgbrewpubonsite;
            }
            if (dynamicsApplication.AdoxioMfgusesneutralgrainspirits != null)
            {
                applicationVM.MfgUsesNeutralGrainSpirits = (YesNoNotApplicable)dynamicsApplication.AdoxioMfgusesneutralgrainspirits;
            }


            if (dynamicsApplication.AdoxioLocatedabovedescription != null)
            {
                applicationVM.LocatedAboveDescription = dynamicsApplication.AdoxioLocatedabovedescription;
            }

            if (dynamicsApplication.AdoxioPatioservicebar != null)
            {
                applicationVM.PatioServiceBar = dynamicsApplication.AdoxioPatioservicebar;
            }

            // Catering yes / no fields
            if (dynamicsApplication.AdoxioPreviouslicenceapplication != null)
            {
                applicationVM.PreviousApplication = dynamicsApplication.AdoxioPreviouslicenceapplication;
            }

            if (dynamicsApplication.AdoxioRuralagencystoreappointment != null)
            {
                applicationVM.RuralAgencyStoreAppointment = dynamicsApplication.AdoxioRuralagencystoreappointment;
            }

            if (dynamicsApplication.AdoxioLiquorindustryconnections != null)
            {
                applicationVM.LiquorIndustryConnections = dynamicsApplication.AdoxioLiquorindustryconnections;
            }

            if (dynamicsApplication.AdoxioOtherbusinessesatthesamelocation != null)
            {
                applicationVM.OtherBusinesses = dynamicsApplication.AdoxioOtherbusinessesatthesamelocation;
            }


            // id
            if (dynamicsApplication.AdoxioApplicationid != null)
            {
                applicationVM.Id = dynamicsApplication.AdoxioApplicationid.ToString();

                // service areas
                var filter = $"_adoxio_applicationid_value eq {dynamicsApplication.AdoxioApplicationid}";
                try
                {
                    IList <MicrosoftDynamicsCRMadoxioServicearea> areas = dynamicsClient.Serviceareas.Get(filter: filter).Value;
                    foreach (MicrosoftDynamicsCRMadoxioServicearea area in areas)
                    {
                        if (area.AdoxioAreacategory == (int?)AdoxioAreaCategories.Service)
                        {
                            applicationVM.ServiceAreas.Add(area.ToViewModel());
                        }
                        else if (area.AdoxioAreacategory == (int?)AdoxioAreaCategories.OutdoorArea)
                        {
                            applicationVM.OutsideAreas.Add(area.ToViewModel());
                        }
                        else if (area.AdoxioAreacategory == (int?)AdoxioAreaCategories.Capacity)
                        {
                            applicationVM.CapacityArea.Add(area.ToViewModel());
                        }
                    }
                }
                catch (HttpOperationException httpOperationException)
                {
                    logger.LogError(httpOperationException, "Error getting service areas.");
                }

                // service hours
                try
                {
                    var appFilter = $"_adoxio_application_value eq {dynamicsApplication.AdoxioApplicationid}";
                    IList <MicrosoftDynamicsCRMadoxioHoursofservice> hours = dynamicsClient.Hoursofservices.Get(filter: appFilter).Value;
                    if (hours.Count > 0)
                    {
                        MicrosoftDynamicsCRMadoxioHoursofservice hourEntity = hours[0];
                        applicationVM.ServiceHoursSundayOpen     = (ServiceHours?)hourEntity.AdoxioSundayopen;
                        applicationVM.ServiceHoursSundayClose    = (ServiceHours?)hourEntity.AdoxioSundayclose;
                        applicationVM.ServiceHoursMondayOpen     = (ServiceHours?)hourEntity.AdoxioMondayopen;
                        applicationVM.ServiceHoursMondayClose    = (ServiceHours?)hourEntity.AdoxioMondayclose;
                        applicationVM.ServiceHoursTuesdayOpen    = (ServiceHours?)hourEntity.AdoxioTuesdayopen;
                        applicationVM.ServiceHoursTuesdayClose   = (ServiceHours?)hourEntity.AdoxioTuesdayclose;
                        applicationVM.ServiceHoursWednesdayOpen  = (ServiceHours?)hourEntity.AdoxioWednesdayopen;
                        applicationVM.ServiceHoursWednesdayClose = (ServiceHours?)hourEntity.AdoxioWednesdayclose;
                        applicationVM.ServiceHoursThursdayOpen   = (ServiceHours?)hourEntity.AdoxioThursdayopen;
                        applicationVM.ServiceHoursThursdayClose  = (ServiceHours?)hourEntity.AdoxioThursdayclose;
                        applicationVM.ServiceHoursFridayOpen     = (ServiceHours?)hourEntity.AdoxioFridayopen;
                        applicationVM.ServiceHoursFridayClose    = (ServiceHours?)hourEntity.AdoxioFridayclose;
                        applicationVM.ServiceHoursSaturdayOpen   = (ServiceHours?)hourEntity.AdoxioSaturdayopen;
                        applicationVM.ServiceHoursSaturdayClose  = (ServiceHours?)hourEntity.AdoxioSaturdayclose;
                    }
                }
                catch (HttpOperationException httpOperationException)
                {
                    logger.LogError(httpOperationException, "Error getting service hours.");
                }
            }

            if (dynamicsApplication.Statuscode != null)
            {
                applicationVM.ApplicationStatus = (AdoxioApplicationStatusCodes)dynamicsApplication.Statuscode;
            }

            if (dynamicsApplication.AdoxioApplicanttype != null)
            {
                applicationVM.ApplicantType = (AdoxioApplicantTypeCodes)dynamicsApplication.AdoxioApplicanttype;
            }

            //get applying person from Contact entity
            if (dynamicsApplication._adoxioApplyingpersonValue != null)
            {
                Guid applyingPersonId = Guid.Parse(dynamicsApplication._adoxioApplyingpersonValue);
                var  contact          = await dynamicsClient.GetContactById(applyingPersonId);

                applicationVM.ApplyingPerson = contact.Fullname;
            }

            if (dynamicsApplication._adoxioApplicantValue != null)
            {
                var applicant = await dynamicsClient.GetAccountByIdAsync(Guid.Parse(dynamicsApplication._adoxioApplicantValue));

                applicationVM.Applicant = applicant.ToViewModel();
            }

            //get license type from Adoxio_licencetype entity
            if (dynamicsApplication._adoxioLicencetypeValue != null)
            {
                Guid adoxio_licencetypeId = Guid.Parse(dynamicsApplication._adoxioLicencetypeValue);
                var  adoxio_licencetype   = dynamicsClient.GetAdoxioLicencetypeById(adoxio_licencetypeId);
                applicationVM.LicenseType = adoxio_licencetype.AdoxioName;
            }

            // get the license sub type.

            if (dynamicsApplication._adoxioLicencesubcategoryidValue != null)
            {
                try
                {
                    var adoxioLicencesubcategory = dynamicsClient.Licencesubcategories.GetByKey(dynamicsApplication._adoxioLicencesubcategoryidValue);
                    applicationVM.LicenceSubCategory = adoxioLicencesubcategory.AdoxioName;
                }
                catch (Exception e)
                {
                    logger.LogError(e, $"Problem getting licence sub category {dynamicsApplication._adoxioLicencesubcategoryidValue}");
                }
            }

            if (dynamicsApplication.AdoxioAppchecklistfinaldecision != null)
            {
                applicationVM.AppChecklistFinalDecision = (AdoxioFinalDecisionCodes)dynamicsApplication.AdoxioAppchecklistfinaldecision;
            }

            //get payment info
            applicationVM.InvoiceTrigger = (GeneralYesNo?)dynamicsApplication.AdoxioInvoicetrigger;
            applicationVM.IsSubmitted    = (dynamicsApplication.AdoxioInvoicetrigger == 1);


            if (dynamicsApplication.AdoxioLicenceFeeInvoice != null)
            {
                applicationVM.LicenceFeeInvoice = dynamicsApplication.AdoxioLicenceFeeInvoice.ToViewModel();
            }

            if (dynamicsApplication.AdoxioAssignedLicence != null)
            {
                applicationVM.AssignedLicence = dynamicsApplication.AdoxioAssignedLicence.ToViewModel(dynamicsClient);
            }

            if (dynamicsApplication.AdoxioApplicationTypeId != null)
            {
                applicationVM.ApplicationType = dynamicsApplication.AdoxioApplicationTypeId.ToViewModel();

                if (!string.IsNullOrEmpty(applicationVM.ApplicationType.FormReference))
                {
                    applicationVM.ApplicationType.DynamicsForm = dynamicsClient.GetSystemformViewModel(cache, logger, applicationVM.ApplicationType.FormReference);
                }
            }
            if (dynamicsApplication.AdoxioApplicationAdoxioTiedhouseconnectionApplication != null)
            {
                var tiedHouse = dynamicsApplication.AdoxioApplicationAdoxioTiedhouseconnectionApplication.FirstOrDefault();
                if (tiedHouse != null)
                {
                    applicationVM.TiedHouse = tiedHouse.ToViewModel();
                }
            }

            if (dynamicsApplication.AdoxioPoliceJurisdictionId != null)
            {
                applicationVM.PoliceJurisdiction = dynamicsApplication.AdoxioPoliceJurisdictionId.ToViewModel();
            }

            if (dynamicsApplication.AdoxioLocalgovindigenousnationid != null)
            {
                var filter        = $"_adoxio_lginlinkid_value eq {dynamicsApplication.AdoxioLocalgovindigenousnationid.AdoxioLocalgovindigenousnationid} and websiteurl ne null";
                var linkedAccount = (await dynamicsClient.Accounts.GetAsync(filter: filter)).Value.FirstOrDefault();
                applicationVM.IndigenousNation = dynamicsApplication.AdoxioLocalgovindigenousnationid.ToViewModel();

                if (linkedAccount != null)
                {
                    applicationVM.IndigenousNation.WebsiteUrl = linkedAccount.Websiteurl;
                }
            }

            applicationVM.PrevPaymentFailed = (dynamicsApplication._adoxioInvoiceValue != null) && (!applicationVM.IsSubmitted);

            return(applicationVM);
        }
        public static void CopyValues(this MicrosoftDynamicsCRMadoxioApplication to, ViewModels.Application from)
        {
            to.AdoxioName = from.Name;
            //to.Adoxio_jobnumber = from.jobNumber;
            to.AdoxioEstablishmentpropsedname       = from.EstablishmentName;
            to.AdoxioEstablishmentaddressstreet     = from.EstablishmentAddressStreet;
            to.AdoxioEstablishmentaddresscity       = from.EstablishmentAddressCity;
            to.AdoxioEstablishmentaddresspostalcode = from.EstablishmentAddressPostalCode;
            // 12-10-2019 - Removed the update to AdoxioAddressCity as the Dynamics workflow handles that.

            to.AdoxioEstablishmentparcelid = from.EstablishmentParcelId;
            to.AdoxioEstablishmentphone    = from.EstablishmentPhone;
            to.AdoxioEstablishmentemail    = from.EstablishmentEmail;

            to.AdoxioContactpersonfirstname = from.ContactPersonFirstName;
            to.AdoxioContactpersonlastname  = from.ContactPersonLastName;
            to.AdoxioRole  = from.ContactPersonRole;
            to.AdoxioEmail = from.ContactPersonEmail;
            to.AdoxioContactpersonphone            = from.ContactPersonPhone;
            to.AdoxioAuthorizedtosubmit            = from.AuthorizedToSubmit;
            to.AdoxioSignatureagreement            = from.SignatureAgreement;
            to.AdoxioAdditionalpropertyinformation = from.AdditionalPropertyInformation;
            to.AdoxioFederalproducernames          = from.FederalProducerNames;

            to.AdoxioInvoicetrigger = (int?)from.InvoiceTrigger;

            to.AdoxioRenewalcriminaloffencecheck     = (int?)from.RenewalCriminalOffenceCheck;
            to.AdoxioRenewalunreportedsaleofbusiness = (int?)from.RenewalUnreportedSaleOfBusiness;
            to.AdoxioRenewalbusinesstype             = (int?)from.RenewalBusinessType;
            to.AdoxioRenewaltiedhouse            = (int?)from.RenewalTiedhouse;
            to.AdoxioRenewalorgleadership        = (int?)from.RenewalOrgLeadership;
            to.AdoxioRenewalkeypersonnel         = (int?)from.Renewalkeypersonnel;
            to.AdoxioRenewalshareholders         = (int?)from.RenewalShareholders;
            to.AdoxioRenewaloutstandingfines     = (int?)from.RenewalOutstandingFines;
            to.AdoxioRenewalbranding             = (int?)from.RenewalBranding;
            to.AdoxioRenewalsignage              = (int?)from.RenewalSignage;
            to.AdoxioRenewalestablishmentaddress = (int?)from.RenewalEstablishmentAddress;
            to.AdoxioRenewalvalidinterest        = (int?)from.RenewalValidInterest;
            to.AdoxioRenewalzoning    = (int?)from.RenewalZoning;
            to.AdoxioRenewalfloorplan = (int?)from.RenewalFloorPlan;
            to.AdoxioRenewalsitemap   = (int?)from.RenewalSiteMap;
            to.AdoxioRenewaltiedhousefederalinterest = (int?)from.TiedhouseFederalInterest;
            to.AdoxioDescription1 = from.Description1;
            to.AdoxioDescription2 = from.Description2;

            //store opening
            to.AdoxioIsreadyworkers                  = from.IsReadyWorkers;
            to.AdoxioIsreadynamebranding             = from.IsReadyNameBranding;
            to.AdoxioIsreadydisplays                 = from.IsReadyDisplays;
            to.AdoxioIsreadyintruderalarm            = from.IsReadyIntruderAlarm;
            to.AdoxioIsreadyfirealarm                = from.IsReadyFireAlarm;
            to.AdoxioIsreadylockedcases              = from.IsReadyLockedCases;
            to.AdoxioIsreadylockedstorage            = from.IsReadyLockedStorage;
            to.AdoxioIsreadyperimeter                = from.IsReadyPerimeter;
            to.AdoxioIsreadyretailarea               = from.IsReadyRetailArea;
            to.AdoxioIsreadystorage                  = from.IsReadyStorage;
            to.AdoxioIsreadyentranceexit             = from.IsReadyExtranceExit;
            to.AdoxioIsreadysurveillancenotice       = from.IsReadySurveillanceNotice;
            to.AdoxioIsreadyproductnotvisibleoutside = from.IsReadyProductNotVisibleOutside;
            to.AdoxioIslocatedingrocerystore         = from.IsLocatedInGroceryStore;
            to.AdoxioEstablishmentopeningdate        = from.Establishmentopeningdate;
            to.AdoxioIsreadyvalidinterest            = from.IsReadyValidInterest;

            to.AdoxioAuthorizedtosubmit = from.AuthorizedToSubmit;
            to.AdoxioSignatureagreement = from.SignatureAgreement;

            to.AdoxioApplicanttype      = (int?)from.ApplicantType;
            to.AdoxioLgzoning           = (int?)from.LgZoning;
            to.AdoxioLgdecisioncomments = from.LGDecisionComments;

            // catering fields
            to.AdoxioPreviouslicenceapplication        = from.PreviousApplication;
            to.AdoxioPreviouslicenceapplicationdetails = from.PreviousApplicationDetails;
            to.AdoxioRuralagencystoreappointment       = from.RuralAgencyStoreAppointment;
            to.AdoxioLiquorindustryconnections         = from.LiquorIndustryConnections;
            to.AdoxioLiquorindustryconnectionsdetails  = from.LiquorIndustryConnectionsDetails;
            to.AdoxioOtherbusinessesatthesamelocation  = from.OtherBusinesses;
            to.AdoxioOtherbusinesssamelocationdetails  = from.OtherBusinessesDetails;
            to.AdoxioIsapplicationcomplete             = (int?)from.IsApplicationComplete;

            to.AdoxioRenewaldui        = (int?)from.RenewalDUI;
            to.AdoxioRenewalthirdparty = (int?)from.RenewalThirdParty;

            to.AdoxioIsownerbusiness              = from.IsOwnerBusiness;
            to.AdoxioIsownerhasvalidinterest      = from.HasValidInterest;
            to.AdoxioIsownerwillhavevalidinterest = from.WillHaveValidInterest;
            to.AdoxioZoningstatus = (int?)from.ZoningStatus;

            to.AdoxioIshaspatio = from.IsHasPatio;

            //lg approval fields
            to.AdoxioLgnameofofficial         = from.LGNameOfOfficial;
            to.AdoxioLgtitleposition          = from.LGTitlePosition;
            to.AdoxioLgcontactphone           = from.LGContactPhone;
            to.AdoxioLgcontactemail           = from.LGContactEmail;
            to.AdoxioLgdecisionsubmissiondate = from.LGDecisionSubmissionDate;
            to.AdoxioLgapprovaldecision       = (int?)from.LGApprovalDecision;

            // Manufacturing fields

            to.AdoxioIspackaging                = from.IsPackaging;
            to.AdoxioMfgpipedinproduct          = (int?)from.MfgPipedInProduct;
            to.AdoxioMfgbrewpubonsite           = (int?)from.MfgBrewPubOnSite;
            to.AdoxioMfgacresoffruit            = from.MfgAcresOfFruit;
            to.AdoxioMfgacresofgrapes           = from.MfgAcresOfGrapes;
            to.AdoxioMfgacresofhoney            = from.MfgAcresOfHoney;
            to.AdoxioMfgmeetsproductionminimum  = from.MfgMeetsProductionMinimum;
            to.AdoxioMfgstepblending            = from.MfgStepBlending;
            to.AdoxioMfgstepcrushing            = from.MfgStepCrushing;
            to.AdoxioMfgstepfiltering           = from.MfgStepFiltering;
            to.AdoxioMfgstepsecfermorcarb       = from.MfgStepSecFermOrCarb;
            to.AdoxioMfgusesneutralgrainspirits = (int?)from.MfgUsesNeutralGrainSpirits;
            to.AdoxioPidlist             = from.PidList;
            to.AdoxioIspermittedinzoning = from.IsPermittedInZoning;

            // here

            // Manufacturing structural change fields

            to.AdoxioPatiocompdescription          = from.PatioCompDescription;
            to.AdoxioPatiolocationdescription      = from.PatioLocationDescription;
            to.AdoxioPatioaccessdescription        = from.PatioAccessDescription;
            to.AdoxioPatioisliquorcarried          = from.PatioIsLiquorCarried;
            to.AdoxioPatioliquorcarrieddescription = from.PatioLiquorCarriedDescription;
            to.AdoxioPatioaccesscontroldescription = from.PatioAccessControlDescription;
            to.AdoxioLocatedabovedescription       = (int?)from.LocatedAboveDescription;
            to.AdoxioPatioservicebar = from.PatioServiceBar;

            to.AdoxioProposedestablishmentisalr = from.IsAlr;
            to.AdoxioHascooleraccess            = from.HasCoolerAccess;



            // comment out this next line as it is causing all application updates to fail (moved to controller)
            //to.AdoxioApplicanttype = (int)Enum.ToObject(typeof(Gov.Lclb.Cllb.Public.ViewModels.Adoxio_applicanttypecodes), from.applicantType);

            //var adoxio_licencetype = dynamicsClient.GetAdoxioLicencetypeByName(from.licenseType).Result;
            //to.AdoxioLicenceType = adoxio_licencetype;
            //to._adoxioLicencetypeValue = adoxio_licencetype.AdoxioLicencetypeid;

            //if (!String.IsNullOrEmpty(from.applicationStatus))
            //{
            //    to.Statuscode = int.Parse(from.applicationStatus);
            //}
            //else
            //{
            //    to.Statecode = null;
            //}
        }
 /// <summary>
 /// Add new entity to adoxio_applications
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// New entity
 /// </param>
 /// <param name='prefer'>
 /// Required in order for the service to return a JSON representation of the
 /// object.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <MicrosoftDynamicsCRMadoxioApplication> CreateAsync(this IApplications operations, MicrosoftDynamicsCRMadoxioApplication body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Add new entity to adoxio_applications
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// New entity
 /// </param>
 /// <param name='prefer'>
 /// Required in order for the service to return a JSON representation of the
 /// object.
 /// </param>
 public static MicrosoftDynamicsCRMadoxioApplication Create(this IApplications operations, MicrosoftDynamicsCRMadoxioApplication body, string prefer = "return=representation")
 {
     return(operations.CreateAsync(body, prefer).GetAwaiter().GetResult());
 }
Example #26
0
        /// <summary>
        /// Update entity in adoxio_applications
        /// </summary>
        /// <param name='adoxioApplicationid'>
        /// key: adoxio_applicationid of adoxio_application
        /// </param>
        /// <param name='body'>
        /// New property values
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> UpdateWithHttpMessagesAsync(string adoxioApplicationid, MicrosoftDynamicsCRMadoxioApplication body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (adoxioApplicationid == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "adoxioApplicationid");
            }
            if (body == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "body");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("adoxioApplicationid", adoxioApplicationid);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_applications({adoxio_applicationid})").ToString();

            _url = _url.Replace("{adoxio_applicationid}", System.Uri.EscapeDataString(adoxioApplicationid));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PATCH");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 204)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Example #27
0
        public static void CreateApplicationDocumentLocation(this IDynamicsClient _dynamicsClient, MicrosoftDynamicsCRMadoxioApplication application, string folderName, string name)
        {
            // now create a document location to link them.
            var parentDocumentLibraryReference = _dynamicsClient.GetDocumentLocationReferenceByRelativeURL("adoxio_application");

            var regardingobjectId = _dynamicsClient.GetEntityURI("adoxio_applications", application.AdoxioApplicationid);

            // Create the SharePointDocumentLocation entity
            var mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation
            {
                RegardingobjectidAdoxioApplicationODataBind             = regardingobjectId,
                ParentsiteorlocationSharepointdocumentlocationODataBind = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference),
                Relativeurl = folderName,
                Description = "Application Files",
                Name        = name
            };

            var sharepointdocumentlocationid = _dynamicsClient.DocumentLocationExistsWithCleanup(mdcsdl);

            if (sharepointdocumentlocationid == null)
            {
                sharepointdocumentlocationid = _dynamicsClient.CreateDocumentLocation(mdcsdl);

                var sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", sharepointdocumentlocationid);

                var oDataId = new Odataid
                {
                    OdataidProperty = sharePointLocationData
                };
                try
                {
                    _dynamicsClient.Applications.AddReference(application.AdoxioApplicationid, "adoxio_application_SharePointDocumentLocations", oDataId);
                }
                catch (HttpOperationException odee)
                {
                    Log.Error(odee, "Error adding reference to SharepointDocumentLocation");
                }
            }
        }
        public async static Task <ViewModels.CovidApplication> ToCovidViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication, IDynamicsClient dynamicsClient, IMemoryCache cache, ILogger logger)
        {
            ViewModels.CovidApplication applicationVM = new ViewModels.CovidApplication()
            {
                Name      = dynamicsApplication.AdoxioName,
                JobNumber = dynamicsApplication.AdoxioJobnumber,
                //get establishment name and address
                EstablishmentName              = dynamicsApplication.AdoxioEstablishmentpropsedname,
                EstablishmentAddressStreet     = dynamicsApplication.AdoxioEstablishmentaddressstreet,
                EstablishmentAddressCity       = dynamicsApplication.AdoxioEstablishmentaddresscity,
                EstablishmentAddressPostalCode = dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentAddress           = dynamicsApplication.AdoxioEstablishmentaddressstreet
                                                 + ", " + dynamicsApplication.AdoxioEstablishmentaddresscity
                                                 + " " + dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentPhone    = dynamicsApplication.AdoxioEstablishmentphone,
                EstablishmentEmail    = dynamicsApplication.AdoxioEstablishmentemail,
                IsApplicationComplete = (GeneralYesNo?)dynamicsApplication.AdoxioIsapplicationcomplete,

                AddressStreet     = dynamicsApplication.AdoxioAddressstreet,
                AddressCity       = dynamicsApplication.AdoxioAddresscity,
                AddressPostalCode = dynamicsApplication.AdoxioAddresspostalcode,

                NameOfApplicant = dynamicsApplication.AdoxioNameofapplicant,



                AuthorizedToSubmit = dynamicsApplication.AdoxioAuthorizedtosubmit,

                //get parcel id
                EstablishmentParcelId = dynamicsApplication.AdoxioEstablishmentparcelid,

                //get additional property info
                AdditionalPropertyInformation = dynamicsApplication.AdoxioAdditionalpropertyinformation,
                AdoxioInvoiceId = dynamicsApplication._adoxioInvoiceValue,

                Description1 = dynamicsApplication.AdoxioDescription1,

                //get contact details
                ContactPersonFirstName = dynamicsApplication.AdoxioContactpersonfirstname,
                ContactPersonLastName  = dynamicsApplication.AdoxioContactpersonlastname,
                ContactPersonRole      = dynamicsApplication.AdoxioRole,
                ContactPersonEmail     = dynamicsApplication.AdoxioEmail,
                ContactPersonPhone     = dynamicsApplication.AdoxioContactpersonphone,

                //get record audit info
                CreatedOn  = dynamicsApplication.Createdon,
                ModifiedOn = dynamicsApplication.Modifiedon,


                ProposedEstablishmentIsAlr = dynamicsApplication.AdoxioProposedestablishmentisalr
                                             //store opening

                                             // Catering fields.
            };



            // id
            if (dynamicsApplication.AdoxioApplicationid != null)
            {
                applicationVM.Id = dynamicsApplication.AdoxioApplicationid.ToString();
            }


            if (dynamicsApplication.AdoxioApplicanttype != null)
            {
                applicationVM.ApplicantType = (AdoxioApplicantTypeCodes)dynamicsApplication.AdoxioApplicanttype;
            }

            //get applying person from Contact entity
            if (dynamicsApplication._adoxioApplyingpersonValue != null)
            {
                Guid applyingPersonId = Guid.Parse(dynamicsApplication._adoxioApplyingpersonValue);
                var  contact          = await dynamicsClient.GetContactById(applyingPersonId);

                applicationVM.ApplyingPerson = contact.Fullname;
            }


            //get license type from Adoxio_licencetype entity
            if (dynamicsApplication._adoxioLicencetypeValue != null)
            {
                Guid adoxio_licencetypeId = Guid.Parse(dynamicsApplication._adoxioLicencetypeValue);
                var  adoxio_licencetype   = dynamicsClient.GetAdoxioLicencetypeById(adoxio_licencetypeId);
                applicationVM.LicenceType = adoxio_licencetype.AdoxioName;
            }



            if (dynamicsApplication.AdoxioApplicationTypeId != null)
            {
                applicationVM.ApplicationType = dynamicsApplication.AdoxioApplicationTypeId.ToViewModel();

                if (!string.IsNullOrEmpty(applicationVM.ApplicationType.FormReference))
                {
                    applicationVM.ApplicationType.DynamicsForm = dynamicsClient.GetSystemformViewModel(cache, logger, applicationVM.ApplicationType.FormReference);
                }
            }

            return(applicationVM);
        }
 /// <summary>
 /// Update entity in adoxio_applications
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='adoxioApplicationid'>
 /// key: adoxio_applicationid
 /// </param>
 /// <param name='body'>
 /// New property values
 /// </param>
 public static void Update(this IApplications operations, string adoxioApplicationid, MicrosoftDynamicsCRMadoxioApplication body)
 {
     operations.UpdateAsync(adoxioApplicationid, body).GetAwaiter().GetResult();
 }
 /// <summary>
 /// Update entity in adoxio_applications
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='adoxioApplicationid'>
 /// key: adoxio_applicationid
 /// </param>
 /// <param name='body'>
 /// New property values
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task UpdateAsync(this IApplications operations, string adoxioApplicationid, MicrosoftDynamicsCRMadoxioApplication body, CancellationToken cancellationToken = default(CancellationToken))
 {
     (await operations.UpdateWithHttpMessagesAsync(adoxioApplicationid, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }