public async Task <IActionResult> UpdateWorker([FromBody] ViewModels.Worker item, string id) { if (id != null && item.id != null && id != item.id) { return(BadRequest()); } // get the contact Guid workerId = Guid.Parse(id); MicrosoftDynamicsCRMadoxioWorker worker = await _dynamicsClient.GetWorkerById(Guid.Parse(item.id)); if (worker == null) { return(new NotFoundResult()); } MicrosoftDynamicsCRMadoxioWorker patchWorker = new MicrosoftDynamicsCRMadoxioWorker(); patchWorker.CopyValues(item); try { await _dynamicsClient.Workers.UpdateAsync(worker.AdoxioWorkerid.ToString(), patchWorker); } catch (OdataerrorException odee) { _logger.LogError("Error updating contact"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } worker = await _dynamicsClient.GetWorkerById(workerId); return(Json(worker.ToViewModel())); }
public async Task <IActionResult> CreateWorker([FromBody] ViewModels.Worker item) { // get UserSettings from the session string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp); // create a new worker. MicrosoftDynamicsCRMadoxioWorker worker = new MicrosoftDynamicsCRMadoxioWorker() { AdoxioIsmanual = 0 // 0 for false - is a portal user. }; worker.CopyValues(item); if (item?.contact?.id == null) { return(BadRequest()); } try { worker = await _dynamicsClient.Workers.CreateAsync(worker); var patchWorker = new MicrosoftDynamicsCRMadoxioWorker(); patchWorker.ContactIdAccountODataBind = _dynamicsClient.GetEntityURI("contacts", item.contact.id); await _dynamicsClient.Workers.UpdateAsync(worker.AdoxioWorkerid.ToString(), patchWorker); } catch (OdataerrorException odee) { _logger.LogError("Error updating contact"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } return(Json(worker)); }
public IActionResult GetWorker(string id) { ViewModels.Worker result = null; if (!string.IsNullOrEmpty(id)) { Guid workerId = Guid.Parse(id); // query the Dynamics system to get the contact record. string filter = $"adoxio_workerid eq {id}"; var fields = new List <string> { "adoxio_ContactId" }; MicrosoftDynamicsCRMadoxioWorker worker = _dynamicsClient.Workers.Get(filter: filter, expand: fields).Value.FirstOrDefault(); if (worker != null) { if (!CurrentUserHasAccessToContactWorkerApplicationOwnedBy(worker?.AdoxioContactId?.Contactid)) { return(NotFound("No access to worker")); } result = worker.ToViewModel(); } else { return(NotFound()); } } else { return(BadRequest()); } return(Json(result)); }
/// <summary> /// Convert a given voteQuestion to a ViewModel /// </summary> public static ViewModels.Worker ToViewModel(this MicrosoftDynamicsCRMadoxioWorker worker) { ViewModels.Worker result = null; if (worker != null) { result = new ViewModels.Worker(); if (worker.AdoxioWorkerid != null) { result.id = worker.AdoxioWorkerid; } if (worker.AdoxioIsldbworker != null) { result.isldbworker = worker.AdoxioIsldbworker == 1; } result.firstname = worker.AdoxioFirstname; result.middlename = worker.AdoxioMiddlename; result.lastname = worker.AdoxioLastname; result.dateofbirth = worker.AdoxioDateofbirth; result.modifiedOn = worker.Modifiedon; if (worker.AdoxioGendercode != null) { result.gender = (ViewModels.Gender)worker.AdoxioGendercode; } if (worker.Statuscode != null) { result.Status = (ViewModels.StatusCode)worker.Statuscode; } if (worker.Statecode != null) { result.StateCode = (ViewModels.StatusCode)worker.Statecode; } result.birthplace = worker.AdoxioBirthplace; result.driverslicencenumber = worker.AdoxioDriverslicencenumber; result.bcidcardnumber = worker.AdoxioBcidcardnumber; result.phonenumber = worker.AdoxioPhonenumber; result.email = worker.AdoxioEmail; if (worker.AdoxioSelfdisclosure != null) { result.selfdisclosure = worker.AdoxioSelfdisclosure == 1; } if (worker.AdoxioTriggerphs != null) { result.triggerphs = worker.AdoxioTriggerphs == 1; } if (worker.AdoxioContactId != null) { result.contact = worker.AdoxioContactId.ToViewModel(); } if (worker.AdoxioPaymentreceived != null) { result.paymentReceived = worker.AdoxioPaymentreceived == 1; } result.paymentRecievedDate = worker.AdoxioPaymentreceiveddate; result.workerId = worker.AdoxioWorkerid; result.fromdate = worker.AdoxioCurrentaddressdatefrom; } return(result); }
public async Task <IActionResult> CreateWorker([FromBody] ViewModels.Worker item) { if (item?.contact?.id == null) { return(BadRequest()); } ViewModels.Worker worker = await CreateWorkerRecord(item); return(new JsonResult(worker)); }
public async Task <IActionResult> UpdateWorker([FromBody] ViewModels.Worker item, string id) { if (id != null && item.id != null && id != item.id) { return(BadRequest()); } // get the contact Guid workerId = Guid.Parse(id); string filter = $"adoxio_workerid eq {id}"; var fields = new List <string> { "adoxio_ContactId" }; MicrosoftDynamicsCRMadoxioWorker worker = _dynamicsClient.Workers.Get(filter: filter, expand: fields).Value.FirstOrDefault(); if (worker == null) { return(new NotFoundResult()); } if (!CurrentUserHasAccessToContactWorkerApplicationOwnedBy(worker?.AdoxioContactId?.Contactid)) { return(NotFound("No access to worker")); } if (worker.Statuscode != (int)ViewModels.StatusCode.NotSubmitted) { return(BadRequest("Applications with this status cannot be updated")); } MicrosoftDynamicsCRMadoxioWorker patchWorker = new MicrosoftDynamicsCRMadoxioWorker(); patchWorker.CopyValues(item); try { await _dynamicsClient.Workers.UpdateAsync(worker.AdoxioWorkerid.ToString(), patchWorker); } catch (OdataerrorException odee) { _logger.LogError("Error updating contact"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw odee; } worker = await _dynamicsClient.GetWorkerById(workerId); return(Json(worker.ToViewModel())); }
public static void CopyHeaderValues(this ViewModels.Worker to, IHeaderDictionary headers) { string smgov_useremail = headers["smgov_useremail"]; // the following fields appear to just have a guid in them, not a driver's licence. string smgov_useridentifier = headers["smgov_useridentifier"]; string smgov_useridentifiertype = headers["smgov_useridentifiertype"]; // birthdate is YYYY-MM-DD string smgov_birthdate = headers["smgov_birthdate"]; // Male / Female / Unknown. string smgov_sex = headers["smgov_sex"]; string smgov_givenname = headers["smgov_givenname"]; string smgov_givennames = headers["smgov_givennames"]; string smgov_surname = headers["smgov_surname"]; if (!string.IsNullOrEmpty(smgov_givenname)) { to.firstname = smgov_givenname; } if (!string.IsNullOrEmpty(smgov_givennames)) { to.middlename = smgov_givennames.Replace(smgov_givenname, "").Trim(); } if (!string.IsNullOrEmpty(smgov_surname)) { to.lastname = smgov_surname; } if (!string.IsNullOrEmpty(smgov_useremail)) { to.email = smgov_useremail; } if (!string.IsNullOrEmpty(smgov_birthdate) && DateTimeOffset.TryParse(smgov_birthdate, out DateTimeOffset tempDate)) { to.dateofbirth = tempDate; } if (!string.IsNullOrEmpty(smgov_sex)) { to.gender = (Gender)GetIntGenderCode(smgov_sex); } }
public async Task <IActionResult> CreateWorker([FromBody] ViewModels.Worker item) { // create a new worker. MicrosoftDynamicsCRMadoxioWorker worker = new MicrosoftDynamicsCRMadoxioWorker { AdoxioIsmanual = 0 // 0 for false - is a portal user. }; worker.CopyValues(item); if (item?.contact?.id == null) { return(BadRequest()); } try { worker = await _dynamicsClient.Workers.CreateAsync(worker); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, "Error creating worker. "); } catch (Exception e) { _logger.LogError(e, "Error creating worker."); } try { var patchWorker = new MicrosoftDynamicsCRMadoxioWorker(); patchWorker.ContactIdAccountODataBind = _dynamicsClient.GetEntityURI("contacts", item.contact.id); await _dynamicsClient.Workers.UpdateAsync(worker.AdoxioWorkerid, patchWorker); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, "Error updating worker. "); } catch (Exception e) { _logger.LogError(e, "Error updating worker."); } return(new JsonResult(worker.ToViewModel())); }
private async Task HandleWorkerLogin(UserSettings userSettings, HttpContext context) { IConfiguration _configuration = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration)); IDynamicsClient _dynamicsClient = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient)); FileManagerClient _fileManagerClient = (FileManagerClient)context.RequestServices.GetService(typeof(FileManagerClient)); // Update worker with latest info from BC Service Card MicrosoftDynamicsCRMadoxioWorkerCollection workerCollection = _dynamicsClient.Workers.Get(filter: $"_adoxio_contactid_value eq {userSettings.ContactId}"); if (workerCollection.Value.Count > 0) { MicrosoftDynamicsCRMadoxioWorker savedWorker = workerCollection.Value[0]; ViewModels.Worker worker = new ViewModels.Worker(); worker.CopyHeaderValues(context.Request.Headers); MicrosoftDynamicsCRMadoxioWorker patchWorker = new MicrosoftDynamicsCRMadoxioWorker() { AdoxioFirstname = worker.firstname, AdoxioLastname = worker.lastname, AdoxioMiddlename = worker.middlename }; if (worker.gender != 0) { patchWorker.AdoxioGendercode = (int)worker.gender; } _dynamicsClient.Workers.Update(savedWorker.AdoxioWorkerid, patchWorker); var updatedWorker = await _dynamicsClient.GetWorkerByIdWithChildren(savedWorker.AdoxioWorkerid); // only create the worker document location if the FEATURE_NO_WET_SIGNATURE setting is blank if (string.IsNullOrEmpty(_configuration["FEATURE_NO_WET_SIGNATURE"])) { // ensure that the worker has a documents folder. await CreateWorkerDocumentLocation(_dynamicsClient, _fileManagerClient, updatedWorker); } } }
public static void CopyValues(this MicrosoftDynamicsCRMadoxioWorker to, ViewModels.Worker from) { if (from.isldbworker != null) { to.AdoxioIsldbworker = from.isldbworker == true ? 1 : 0; } to.AdoxioFirstname = from.firstname; to.AdoxioMiddlename = from.middlename; to.AdoxioLastname = from.lastname; to.AdoxioDateofbirth = from.dateofbirth; if (from.gender != 0) { to.AdoxioGendercode = (int?)from.gender; } else { to.AdoxioGendercode = null; } to.AdoxioBirthplace = from.birthplace; to.AdoxioDriverslicencenumber = from.driverslicencenumber; to.AdoxioBcidcardnumber = from.bcidcardnumber; to.AdoxioPhonenumber = from.phonenumber; to.AdoxioEmail = from.email; if (from.selfdisclosure != null) { to.AdoxioSelfdisclosure = from.selfdisclosure == true ? 1 : 0; } if (from.triggerphs != null) { to.AdoxioTriggerphs = from.triggerphs == true ? 1 : 0; } if (from.paymentReceived != null) { to.AdoxioPaymentreceived = from.paymentReceived == true ? 1 : 0; } to.AdoxioPaymentreceiveddate = from.paymentRecievedDate; to.AdoxioWorkerid = from.workerId; }
// creates a worker record and links it to the contact with id = item.contact.id private async Task <ViewModels.Worker> CreateWorkerRecord(ViewModels.Worker item) { if (item?.contact?.id == null) { throw new ArgumentNullException(nameof(item.contact.id)); } MicrosoftDynamicsCRMadoxioWorker worker = new MicrosoftDynamicsCRMadoxioWorker(); try { // create the worker worker.AdoxioIsmanual = 0; // 0 for false - is a portal user. worker.CopyValues(item); worker = await _dynamicsClient.Workers.CreateAsync(worker).ConfigureAwait(true); // add contact reference to the worker record var patchWorker = new MicrosoftDynamicsCRMadoxioWorker(); patchWorker.ContactIdAccountODataBind = _dynamicsClient.GetEntityURI("contacts", item.contact.id); await _dynamicsClient.Workers.UpdateAsync(worker.AdoxioWorkerid, patchWorker).ConfigureAwait(true); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, "Error updating worker. "); throw; } catch (Exception e) { _logger.LogError(e, "Error updating worker."); throw; } var result = worker.ToViewModel(); return(worker.ToViewModel()); }
public async Task <IActionResult> GetWorkers(string contactId) { List <ViewModels.Worker> results = new List <ViewModels.Worker>(); if (!CurrentUserHasAccessToContactWorkerApplicationOwnedBy(contactId)) { return(NotFound("No access to contact")); } if (!string.IsNullOrEmpty(contactId)) { Guid id = Guid.Parse(contactId); // query the Dynamics system to get the contact record. string filter = $"_adoxio_contactid_value eq {contactId}"; var fields = new List <string> { "adoxio_ContactId" }; List <MicrosoftDynamicsCRMadoxioWorker> workers = _dynamicsClient.Workers.Get(filter: filter, expand: fields).Value.ToList(); if (workers != null) { workers.ForEach(w => { results.Add(w.ToViewModel()); }); // if there is not worker verification record, create one if (results.Count() == 0) { // query the Dynamics system to get the contact record. var contact = await _dynamicsClient.GetContactById(id); if (contact != null) { var worker = new ViewModels.Worker { firstname = contact.Firstname, middlename = contact.Middlename, lastname = contact.Lastname, contact = new ViewModels.Contact() { id = contactId } }; worker = await this.CreateWorkerRecord(worker); worker.contact = contact.ToViewModel(); results.Add(worker); } } } else { return(new NotFoundResult()); } } else { return(BadRequest()); } return(new JsonResult(results)); }
/// <summary> /// Process Authentication Request /// </summary> /// <returns></returns> protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { // get siteminder headers _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential"); SiteMinderAuthOptions options = new SiteMinderAuthOptions(); bool isDeveloperLogin = false; bool isBCSCDeveloperLogin = false; try { ClaimsPrincipal principal; HttpContext context = Request.HttpContext; IConfiguration _configuration = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration)); IDynamicsClient _dynamicsClient = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient)); FileManagerClient _fileManagerClient = (FileManagerClient)context.RequestServices.GetService(typeof(FileManagerClient)); IWebHostEnvironment hostingEnv = (IWebHostEnvironment)context.RequestServices.GetService(typeof(IWebHostEnvironment)); UserSettings userSettings = new UserSettings(); if (!string.IsNullOrEmpty(_configuration["FEATURE_DISABLE_LOGIN"])) { return(AuthenticateResult.Fail(options.LoginDisabledError)); } string userId = null; string devCompanyId = null; string siteMinderGuid = ""; string siteMinderBusinessGuid = ""; string siteMinderUserType = ""; // ************************************************** // If this is an Error or Authentiation API - Ignore // ************************************************** string url = context.Request.GetDisplayUrl().ToLower(); if (url.Contains(".js")) { return(AuthenticateResult.NoResult()); } // ************************************************** // Check if we have a Dev Environment Cookie // ************************************************** if (!hostingEnv.IsProduction()) { // check for a fake BCeID login in dev mode string temp = context.Request.Cookies[options.DevAuthenticationTokenKey]; if (string.IsNullOrEmpty(temp)) // could be an automated test user. { temp = context.Request.Headers["DEV-USER"]; } if (!string.IsNullOrEmpty(temp)) { if (temp.Contains("::")) { var temp2 = temp.Split("::"); userId = temp2[0]; if (temp2.Length >= 2) { devCompanyId = temp2[1]; } else { devCompanyId = temp2[0]; } } else { userId = temp; devCompanyId = temp; } isDeveloperLogin = true; _logger.LogDebug("Got user from dev cookie = " + userId + ", company = " + devCompanyId); } else { // same set of tests for a BC Services Card dev login temp = context.Request.Cookies[options.DevBCSCAuthenticationTokenKey]; if (string.IsNullOrEmpty(temp)) // could be an automated test user. { temp = context.Request.Headers["DEV-BCSC-USER"]; } if (!string.IsNullOrEmpty(temp)) { userId = temp; isBCSCDeveloperLogin = true; _logger.LogDebug("Got user from dev cookie = " + userId); } } } // ************************************************** // Check if the user session is already created // ************************************************** try { _logger.LogDebug("Checking user session"); userSettings = UserSettings.ReadUserSettings(context); _logger.LogDebug("UserSettings found: " + userSettings.GetJson()); } catch { //do nothing _logger.LogDebug("No UserSettings found"); } // is user authenticated - if so we're done if ((userSettings.UserAuthenticated && string.IsNullOrEmpty(userId)) || (userSettings.UserAuthenticated && !string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(userSettings.UserId) && userSettings.UserId == userId)) { _logger.LogDebug("User already authenticated with active session: " + userSettings.UserId); principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType); return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme))); } string smgov_userdisplayname = context.Request.Headers["smgov_userdisplayname"]; if (!string.IsNullOrEmpty(smgov_userdisplayname)) { userSettings.UserDisplayName = smgov_userdisplayname; } string smgov_businesslegalname = context.Request.Headers["smgov_businesslegalname"]; if (!string.IsNullOrEmpty(smgov_businesslegalname)) { userSettings.BusinessLegalName = smgov_businesslegalname; } // ************************************************** // Authenticate based on SiteMinder Headers // ************************************************** _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential"); // At this point userID would only be set if we are logging in through as a DEV user if (string.IsNullOrEmpty(userId)) { _logger.LogDebug("Getting user data from headers"); userId = context.Request.Headers[options.SiteMinderUserNameKey]; if (string.IsNullOrEmpty(userId)) { userId = context.Request.Headers[options.SiteMinderUniversalIdKey]; } siteMinderGuid = context.Request.Headers[options.SiteMinderUserGuidKey]; siteMinderBusinessGuid = context.Request.Headers[options.SiteMinderBusinessGuidKey]; siteMinderUserType = context.Request.Headers[options.SiteMinderUserTypeKey]; // ************************************************** // Validate credentials // ************************************************** if (string.IsNullOrEmpty(userId)) { _logger.LogDebug(options.MissingSiteMinderUserIdError); return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError)); } if (string.IsNullOrEmpty(siteMinderGuid)) { _logger.LogDebug(options.MissingSiteMinderGuidError); return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError)); } if (string.IsNullOrEmpty(siteMinderUserType)) { _logger.LogDebug(options.MissingSiteMinderUserTypeError); return(AuthenticateResult.Fail(options.MissingSiteMinderUserTypeError)); } } else // DEV user, setup a fake session and SiteMinder headers. { if (isDeveloperLogin) { _logger.LogDebug("Generating a Development user"); userSettings.BusinessLegalName = devCompanyId + " TestBusiness"; userSettings.UserDisplayName = userId + " TestUser"; siteMinderGuid = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString(); siteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString(); siteMinderUserType = "Business"; } else if (isBCSCDeveloperLogin) { _logger.LogDebug("Generating a Development BC Services user"); userSettings.BusinessLegalName = null; userSettings.UserDisplayName = userId + " Associate"; siteMinderGuid = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString(); siteMinderBusinessGuid = null; siteMinderUserType = "VerifiedIndividual"; } } // Previously the code would do a database lookup here. However there is no backing database for the users table now, // so we just do a Dynamics lookup on the siteMinderGuid. _logger.LogDebug("Loading user external id = " + siteMinderGuid); // 3/18/2020 - Note that LoadUser will now work if there is a match on the guid, as well as a match on name in a case where there is no guid. userSettings.AuthenticatedUser = await _dynamicsClient.LoadUser(siteMinderGuid, context.Request.Headers, _logger); _logger.LogDebug("After getting authenticated user = "******" (" + userId + ")"); return(AuthenticateResult.Fail(options.InactivegDbUserIdError)); } if (userSettings.AuthenticatedUser != null && !String.IsNullOrEmpty(siteMinderUserType)) { userSettings.AuthenticatedUser.UserType = siteMinderUserType; } userSettings.UserType = siteMinderUserType; // This line gets the various claims for the current user. ClaimsPrincipal userPrincipal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType); // ************************************************** // Create authenticated user // ************************************************** _logger.LogDebug("Authentication successful: " + userId); _logger.LogDebug("Setting identity and creating session for: " + userId); // create session info for the current user userSettings.UserId = userId; userSettings.UserAuthenticated = true; userSettings.IsNewUserRegistration = userSettings.AuthenticatedUser == null; // set other session info userSettings.SiteMinderGuid = siteMinderGuid; userSettings.SiteMinderBusinessGuid = siteMinderBusinessGuid; _logger.LogDebug("Before getting contact and account ids = " + userSettings.GetJson()); if (userSettings.AuthenticatedUser != null) { userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString(); // ensure that the given account has a documents folder. if (siteMinderBusinessGuid != null) // BCeID user { var contact = _dynamicsClient.GetContactByExternalId(userSettings.ContactId); if (contact == null) { // try by other means. var contactVM = new Public.ViewModels.Contact(); contactVM.CopyHeaderValues(context.Request.Headers); contact = _dynamicsClient.GetContactByContactVmBlankSmGuid(contactVM); } if (contact != null && contact.Contactid != null) { await CreateContactDocumentLocation(_dynamicsClient, _fileManagerClient, contact); } var account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(siteMinderBusinessGuid); if (account == null) { // try by other means. account = _dynamicsClient.GetAccountByLegalName(userSettings.BusinessLegalName); } if (account != null && account.Accountid != null) { userSettings.AccountId = account.Accountid; userSettings.AuthenticatedUser.AccountId = Guid.Parse(account.Accountid); // ensure that the given account has a documents folder. await CreateAccountDocumentLocation(_dynamicsClient, _fileManagerClient, account); } } } if (!hostingEnv.IsProduction() && (isDeveloperLogin || isBCSCDeveloperLogin)) { _logger.LogDebug("DEV MODE Setting identity and creating session for: " + userId); if (isDeveloperLogin) { userSettings.BusinessLegalName = devCompanyId + " TestBusiness"; userSettings.UserDisplayName = userId + " TestUser"; // add generated guids userSettings.SiteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString(); userSettings.SiteMinderGuid = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString(); } else if (isBCSCDeveloperLogin) { userSettings.BusinessLegalName = null; userSettings.UserDisplayName = userId + " Associate"; // add generated guids userSettings.SiteMinderBusinessGuid = null; userSettings.SiteMinderGuid = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString(); } if (userSettings.IsNewUserRegistration) { if (isDeveloperLogin) { // add generated guids // set to null to indicate that the user is still registering the account userSettings.AccountId = null; userSettings.ContactId = null; } else if (isBCSCDeveloperLogin) { // set to null for now userSettings.AccountId = null; userSettings.ContactId = null; } _logger.LogDebug("New user registration:" + userSettings.UserDisplayName); _logger.LogDebug("userSettings.SiteMinderBusinessGuid:" + userSettings.SiteMinderBusinessGuid); _logger.LogDebug("userSettings.SiteMinderGuid:" + userSettings.SiteMinderGuid); _logger.LogDebug("userSettings.AccountId:" + userSettings.AccountId); _logger.LogDebug("userSettings.ContactId:" + userSettings.ContactId); } // Set account ID from authenticated user else if (userSettings.AuthenticatedUser != null) { // populate the business GUID. if (string.IsNullOrEmpty(userSettings.AccountId)) { userSettings.AccountId = userSettings.AuthenticatedUser.AccountId.ToString(); } if (string.IsNullOrEmpty(userSettings.ContactId)) { userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString(); } _logger.LogDebug("Returning user:"******"userSettings.AccountId:" + userSettings.AccountId); _logger.LogDebug("userSettings.ContactId:" + userSettings.ContactId); } } // add the worker settings if it is a new user. if (userSettings.IsNewUserRegistration) { userSettings.NewWorker = new ViewModels.Worker(); userSettings.NewWorker.CopyHeaderValues(context.Request.Headers); userSettings.NewContact = new ViewModels.Contact(); userSettings.NewContact.CopyHeaderValues(context.Request.Headers); if (isBCSCDeveloperLogin) { userSettings.NewWorker.firstname = userId; userSettings.NewWorker.lastname = "Associate"; userSettings.NewContact.firstname = userId; userSettings.NewContact.lastname = "Associate"; } } else if (siteMinderUserType == "VerifiedIndividual") { // Verified individual is from BC Service Card which means it's a worker // Update contact and worker with latest info from BC Service Card MicrosoftDynamicsCRMadoxioWorkerCollection workerCollection = _dynamicsClient.Workers.Get(filter: $"_adoxio_contactid_value eq {userSettings.ContactId}"); if (workerCollection.Value.Count > 0) { MicrosoftDynamicsCRMadoxioWorker savedWorker = workerCollection.Value[0]; ViewModels.Contact contact = new ViewModels.Contact(); contact.CopyHeaderValues(context.Request.Headers); MicrosoftDynamicsCRMcontact savedContact = _dynamicsClient.Contacts.GetByKey(userSettings.ContactId); if (savedContact.Address1Line1 != null && savedContact.Address1Line1 != contact.address1_line1) { MicrosoftDynamicsCRMadoxioPreviousaddress prevAddress = new MicrosoftDynamicsCRMadoxioPreviousaddress() { AdoxioStreetaddress = savedContact.Address1Line1, AdoxioProvstate = savedContact.Address1Stateorprovince, AdoxioCity = savedContact.Address1City, AdoxioCountry = savedContact.Address1Country, AdoxioPostalcode = savedContact.Address1Postalcode, ContactIdODataBind = _dynamicsClient.GetEntityURI("contacts", savedContact.Contactid) }; _dynamicsClient.Previousaddresses.Create(prevAddress); } _dynamicsClient.Contacts.Update(userSettings.ContactId, contact.ToModel()); ViewModels.Worker worker = new ViewModels.Worker(); worker.CopyHeaderValues(context.Request.Headers); MicrosoftDynamicsCRMadoxioWorker patchWorker = new MicrosoftDynamicsCRMadoxioWorker() { AdoxioFirstname = worker.firstname, AdoxioLastname = worker.lastname, AdoxioMiddlename = worker.middlename }; if (worker.gender != 0) { patchWorker.AdoxioGendercode = (int)worker.gender; } _dynamicsClient.Workers.Update(savedWorker.AdoxioWorkerid, patchWorker); var updatedWorker = await _dynamicsClient.GetWorkerByIdWithChildren(savedWorker.AdoxioWorkerid); // only create the worker document location if the FEATURE_NO_WET_SIGNATURE setting is blank if (string.IsNullOrEmpty(_configuration["FEATURE_NO_WET_SIGNATURE"])) { // ensure that the worker has a documents folder. await CreateWorkerDocumentLocation(_dynamicsClient, _fileManagerClient, updatedWorker); } } } // ************************************************** // Update user settings // ************************************************** UserSettings.SaveUserSettings(userSettings, context); // done! principal = userPrincipal; return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme))); } catch (Exception exception) { _logger.LogError(exception.Message); throw; } }
public static void CopyValues(this MicrosoftDynamicsCRMadoxioWorker to, ViewModels.Worker from) { to.AdoxioPhonenumber = from.phonenumber; to.AdoxioEmail = from.email; to.CopyValuesNoEmailPhone(from); }
public async Task <IActionResult> VerifyWorkerPaymentStatus(string workerId) { MicrosoftDynamicsCRMadoxioWorker worker = await GetDynamicsWorker(workerId); if (worker == null) { return(NotFound()); } // load the invoice for this application string invoiceId = worker._adoxioInvoiceValue; _logger.LogError("Found invoice for application = " + invoiceId); MicrosoftDynamicsCRMinvoice invoice = await _dynamicsClient.GetInvoiceById(Guid.Parse(invoiceId)); var ordernum = invoice.AdoxioTransactionid; var orderamt = invoice.Totalamount; var response = await _bcep.ProcessPaymentResponse(ordernum, workerId); response["invoice"] = invoice.Invoicenumber; foreach (var key in response.Keys) { _logger.LogError(">>>>>" + key + ":" + response[key]); } /* * - if the invoice status is not "New", skip * - we will update the Invoice status to "Complete" (if paid) or "Cancelled" (if payment was rejected) * - if payment is successful, we will also set the Application "Payment Received" to "Y" and "Method" to "Credit Card" */ if (invoice.Statecode == (int?)Adoxio_invoicestates.New || invoice.Statecode == null) { _logger.LogError("Processing invoice with status New"); ViewModels.Invoice vmi = invoice.ToViewModel(); MicrosoftDynamicsCRMinvoice invoice2 = new MicrosoftDynamicsCRMinvoice(); invoice2.CopyValues(vmi); ViewModels.Worker workerVM = worker.ToViewModel(); var patchWorker = new MicrosoftDynamicsCRMadoxioWorker(); patchWorker.CopyValues(workerVM); // if payment was successful: var pay_status = response["trnApproved"]; if (pay_status == "1") { _logger.LogError("Transaction approved"); // set invoice status to Complete invoice2.Statecode = (int?)Adoxio_invoicestates.Paid; invoice2.Statuscode = (int?)Adoxio_invoicestatuses.Paid; invoice2.AdoxioReturnedtransactionid = response["trnId"]; _dynamicsClient.Invoices.Update(invoice2.Invoiceid, invoice2); // set the Application payment status patchWorker.AdoxioPaymentreceived = 1; patchWorker.AdoxioPaymentreceiveddate = DateTime.UtcNow; //patchWorker.AdoxioPaymentmethod = (int?)Adoxio_paymentmethods.CC; //patchWorker.AdoxioAppchecklistpaymentreceived = (int?)ViewModels.GeneralYesNo.Yes; _dynamicsClient.Workers.Update(workerId, patchWorker); patchWorker = await GetDynamicsWorker(workerId); } // if payment failed: else { _logger.LogError("Transaction NOT approved"); // set invoice status to Cancelled invoice2.Statecode = (int?)Adoxio_invoicestates.Cancelled; invoice2.Statuscode = (int?)Adoxio_invoicestatuses.Cancelled; _dynamicsClient.Invoices.Update(invoice2.Invoiceid, invoice2); // set the Application invoice status back to No patchWorker.AdoxioInvoicetrigger = (int?)ViewModels.GeneralYesNo.No; // don't clear the invoice, leave the previous "Cancelled" so we can report status //adoxioApplication2._adoxioInvoiceValue = null; //adoxioApplication2.AdoxioInvoice = null; _dynamicsClient.Workers.Update(workerId, patchWorker); patchWorker = await GetDynamicsWorker(workerId); } } else { // that can happen if we are re-validating a completed invoice (paid or cancelled) _logger.LogError("Invoice status is not New, skipping updates ..."); } return(Json(response)); }
public async Task <IActionResult> GetWorkerPaymentUrl(string workerId) { _logger.LogError($"Called GetWorkerPaymentUrl({workerId})"); // get the application and confirm access (call parse to ensure we are getting a valid id) Guid applicationId = Guid.Parse(workerId); MicrosoftDynamicsCRMadoxioWorker worker = await GetDynamicsWorker(workerId); if (worker == null) { return(NotFound()); } // set the application invoice trigger to create an invoice ViewModels.Worker vm = worker.ToViewModel(); MicrosoftDynamicsCRMadoxioWorker patchWorker = new MicrosoftDynamicsCRMadoxioWorker(); patchWorker.CopyValues(vm); // this is the money - setting this flag to "Y" triggers a dynamics workflow that creates an invoice patchWorker.AdoxioInvoicetrigger = (int?)ViewModels.GeneralYesNo.Yes; _dynamicsClient.Workers.Update(workerId, patchWorker); patchWorker = await GetDynamicsWorker(workerId); // now load the invoice for this application to get the pricing string invoiceId = patchWorker._adoxioInvoiceValue; int retries = 0; while (retries < 10 && (invoiceId == null || invoiceId.Length == 0)) { // should happen immediately, but ... // pause and try again - in case Dynamics is slow ... retries++; _logger.LogError("No invoice found, retry = " + retries); System.Threading.Thread.Sleep(1000); invoiceId = patchWorker._adoxioInvoiceValue; } _logger.LogError("Created invoice for application = " + invoiceId); /* * When the applicant submits their Application, we will set the application "Application Invoice Trigger" to "Y" - this will trigger a workflow that will create the Invoice * - we will then re-query the Application to get the Invoice number, * - and then query the Invoice to get the amount * - the Invoice will also contain a Transaction Id (starting at 0500000000) * - the Invoice status will be New * Notes: * - If there is already an invoice with Status New, don't need to create a new Invoice * - If there is already an invoice with Status Complete, it is an error (can't pay twice) * - We will deal with the history later (i.e. there can be multiple "Cancelled" Invoices - we need to keep them for reconciliation but we don't need them for MVP */ MicrosoftDynamicsCRMinvoice invoice = await _dynamicsClient.GetInvoiceById(Guid.Parse(invoiceId)); // dynamics creates a unique transaction id per invoice, used as the "order number" for payment var ordernum = invoice.AdoxioTransactionid; // dynamics determines the amount based on the licence type of the application var orderamt = invoice.Totalamount; Dictionary <string, string> redirectUrl; redirectUrl = new Dictionary <string, string>(); var redirectPath = Configuration["BASE_URI"] + Configuration["BASE_PATH"] + Configuration["BCEP_CONF_PATH_WORKER"]; redirectUrl["url"] = _bcep.GeneratePaymentRedirectUrl(ordernum, workerId, String.Format("{0:0.00}", orderamt), redirectPath); _logger.LogError(">>>>>" + redirectUrl["url"]); return(Json(redirectUrl)); }
public static void CopyValuesNoEmailPhone(this MicrosoftDynamicsCRMadoxioWorker to, ViewModels.Worker from) { if (from.isldbworker != null) { to.AdoxioIsldbworker = from.isldbworker == true ? 1 : 0; } to.AdoxioFirstname = from.firstname; to.AdoxioMiddlename = from.middlename; to.AdoxioLastname = from.lastname; to.AdoxioDateofbirth = from.dateofbirth; if (from.gender != 0) { to.AdoxioGendercode = (int?)from.gender; } else { to.AdoxioGendercode = null; } if (from.Status != 0) { to.Statuscode = (int?)from.Status; } else { to.Statuscode = null; } if (from.StateCode != 0) { to.Statecode = (int?)from.StateCode; } else { to.Statecode = null; } to.AdoxioBirthplace = from.birthplace; to.AdoxioDriverslicencenumber = from.driverslicencenumber; to.AdoxioBcidcardnumber = from.bcidcardnumber; if (from.selfdisclosure != null) { to.AdoxioSelfdisclosure = from.selfdisclosure == true ? 1 : 0; } if (from.triggerphs != null) { to.AdoxioTriggerphs = from.triggerphs == true ? 1 : 0; } if (from.paymentReceived != null) { to.AdoxioPaymentreceived = from.paymentReceived == true ? 1 : 0; } to.AdoxioPaymentreceiveddate = from.paymentRecievedDate; to.AdoxioWorkerid = from.workerId; to.AdoxioCurrentaddressdatefrom = from.fromdate; to.AdoxioConsenttosecurityscreening = from.ConsentToSecurityScreening; to.AdoxioCertifyinformationiscorrect = from.CertifyInformationIsCorrect; to.AdoxioElectronicsignature = from.ElectronicSignature; to.AdoxioConsentvalidated = (int?)from.ConsentValidated; }
public async System.Threading.Tasks.Task TestBirthdate() { string initialName = "TestFirst"; string changedName = "ChangedName"; string changedEmail = "*****@*****.**"; string service = "worker"; // January 1, 1970 - 00:00 with Pacific time. // note that this field expects no time. DateTimeOffset birthDate = DateTimeOffset.Parse("01/01/1970 00:00 -8:00"); // register and login as our first user var loginUser1 = randomNewUserName("TestServiceCardUser", 6); await ServiceCardLogin(loginUser1, loginUser1); // C - Create var request = new HttpRequestMessage(HttpMethod.Post, $"/api/contact"); ViewModels.Contact contactVM = new ViewModels.Contact() { firstname = initialName, middlename = "TestMiddle", lastname = "TestLst", emailaddress1 = "*****@*****.**", Birthdate = birthDate, Gender = ViewModels.Gender.Other }; // the contact service expects certain headers to exist for creation. request.Headers.Add("SMGOV_USEREMAIL", contactVM.emailaddress1); request.Headers.Add("SMGOV_GIVENNAME", contactVM.firstname); request.Headers.Add("SMGOV_SURNAME", contactVM.lastname); string jsonString = JsonConvert.SerializeObject(contactVM); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); jsonString = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); contactVM = JsonConvert.DeserializeObject <ViewModels.Contact>(jsonString); request = new HttpRequestMessage(HttpMethod.Post, $"/api/{service}"); ViewModels.Worker workerVM = new ViewModels.Worker() { firstname = contactVM.firstname, middlename = contactVM.lastname, lastname = contactVM.lastname, dateofbirth = contactVM.Birthdate, email = contactVM.emailaddress1, contact = contactVM, gender = ViewModels.Gender.Other }; jsonString = JsonConvert.SerializeObject(workerVM); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); jsonString = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); workerVM = JsonConvert.DeserializeObject <ViewModels.Worker>(jsonString); // R -Read request = new HttpRequestMessage(HttpMethod.Get, $"/api/{service}/{workerVM.id}"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); workerVM = JsonConvert.DeserializeObject <ViewModels.Worker>(jsonString); Assert.NotNull(workerVM?.id); Assert.Equal(birthDate, workerVM.contact.Birthdate); Assert.Equal(birthDate, workerVM.dateofbirth.Value); // D - Delete request = new HttpRequestMessage(HttpMethod.Post, $"/api/{service}/" + workerVM.id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // second delete should return a 404. request = new HttpRequestMessage(HttpMethod.Post, $"/api/{service}/" + workerVM.id + "/delete"); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, $"/api/{service}/" + workerVM.id); response = await _client.SendAsync(request); jsonString = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); await Logout(); }