public async Task <IActionResult> GetDynamicsApplication(string id) { // 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); ViewModels.AdoxioApplication result = null; var dynamicsApplication = await _dynamicsClient.GetApplicationById(Guid.Parse(id)); if (dynamicsApplication == null) { return(NotFound()); } else { if (!CurrentUserHasAccessToApplicationOwnedBy(dynamicsApplication._adoxioApplicantValue)) { return(new NotFoundResult()); } result = await dynamicsApplication.ToViewModel(_dynamicsClient); } return(Json(result)); }
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 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 async Task <JsonResult> GetDynamicsApplications() { // create a DataServiceCollection to add the record DataServiceCollection <Contexts.Microsoft.Dynamics.CRM.Adoxio_application> ApplicationCollection = new DataServiceCollection <Contexts.Microsoft.Dynamics.CRM.Adoxio_application>(_system); // get all applications in Dynamics filtered by the applying person //var dynamicsApplicationList = await _system.Adoxio_applications.AddQueryOption("$filter", "_adoxio_applyingperson_value eq 7d4a5b20-e352-e811-8140-480fcfeac941").ExecuteAsync(); // get all applications in Dynamics var dynamicsApplicationList = await _system.Adoxio_applications.ExecuteAsync(); List <ViewModels.AdoxioApplication> adoxioApplications = new List <AdoxioApplication>(); ViewModels.AdoxioApplication adoxioApplication = null; if (dynamicsApplicationList != null) { foreach (var dynamicsApplication in dynamicsApplicationList) { adoxioApplication = new ViewModels.AdoxioApplication(); adoxioApplication.name = dynamicsApplication.Adoxio_name; //adoxioApplication.applyingPerson = dynamicsApplication.Adoxio_ApplyingPerson.Adoxio_contact_adoxio_application_ApplyingPerson.ToString(); Guid?applyingPersonId = dynamicsApplication._adoxio_applyingperson_value; if (applyingPersonId != null) { // fetch a contact Contexts.Microsoft.Dynamics.CRM.Contact contact = await _system.Contacts.ByKey(contactid : applyingPersonId).GetValueAsync(); adoxioApplication.applyingPerson = contact.Fullname; } adoxioApplication.jobNumber = dynamicsApplication.Adoxio_jobnumber; Guid?adoxio_licencetypeId = dynamicsApplication._adoxio_licencetype_value; if (adoxio_licencetypeId != null) { Adoxio_licencetype adoxio_licencetype = await _system.Adoxio_licencetypes.ByKey(adoxio_licencetypeid : adoxio_licencetypeId).GetValueAsync(); adoxioApplication.licenseType = adoxio_licencetype.Adoxio_name; } adoxioApplications.Add(adoxioApplication); } } return(Json(adoxioApplications)); }
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))); }
public static async Task <ViewModels.AdoxioApplication> GetLicenceApplication(HttpClient _client, string applicationId, bool expectSuccess) { var request = new HttpRequestMessage(HttpMethod.Get, "/api/adoxioapplication/" + applicationId); var response = await _client.SendAsync(request); if (expectSuccess) { response.EnsureSuccessStatusCode(); var jsonString = await response.Content.ReadAsStringAsync(); ViewModels.AdoxioApplication responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); return(responseViewModel); } else { Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); var _discard = await response.Content.ReadAsStringAsync(); return(null); } }
public static async Task <ViewModels.AdoxioApplication> CreateLicenceApplication(HttpClient _client, ViewModels.Account currentAccount) { var request = new HttpRequestMessage(HttpMethod.Post, "/api/adoxioapplication"); ViewModels.AdoxioApplication viewmodel_application = new ViewModels.AdoxioApplication() { licenseType = "Cannabis Retail Store", //*Mandatory field **This is an entity** E.g.Cannabis Retail Store applicantType = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation, //*Mandatory (label=business type) registeredEstablishment = ViewModels.GeneralYesNo.No, //*Mandatory (Yes=1, No=0) applicant = currentAccount, //account establishmentName = "Not a Dispensary", establishmentAddress = "123 Any Street, Victoria, BC, V1X 1X1", establishmentaddressstreet = "123 Any Street", establishmentaddresscity = "Victoria, BC", establishmentaddresspostalcode = "V1X 1X1" }; var jsonString = JsonConvert.SerializeObject(viewmodel_application); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); jsonString = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); // parse as JSON. ViewModels.AdoxioApplication responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); //Assert.Equal("Applying Person", responseViewModel.applyingPerson); Assert.Equal("Not a Dispensary", responseViewModel.establishmentName); Assert.Equal("Victoria, BC", responseViewModel.establishmentaddresscity); Assert.Equal("V1X 1X1", responseViewModel.establishmentaddresspostalcode); return(responseViewModel); }
//[Fact] public async System.Threading.Tasks.Task UserCantAccessAnotherUsersInvoices() { // verify (before we log in) that we are not logged in await GetCurrentUserIsUnauthorized(); // register as a new user (creates an account and contact) var loginUser1 = randomNewUserName("NewSecUser1", 6); var businessName1 = randomNewUserName(loginUser1, 6); var strId1 = await LoginAndRegisterAsNewUser(loginUser1, businessName1); // verify the current user represents our new user ViewModels.User user1 = await GetCurrentUser(); Assert.Equal(user1.name, loginUser1 + " TestUser"); Assert.Equal(user1.businessname, businessName1 + " TestBusiness"); // fetch our current account ViewModels.Account account1 = await GetAccountForCurrentUser(); ViewModels.AdoxioLegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client); Assert.Equal(user1.accountid, account1.id); // *** create some license applications and invoices ViewModels.AdoxioApplication application1 = await SecurityHelper.CreateLicenceApplication(_client, account1); Assert.NotNull(application1); var tmp = await SecurityHelper.GetLicenceApplication(_client, application1.id, true); Assert.NotNull(tmp); // create invoices Dictionary <string, string> values = await SecurityHelper.PayLicenceApplicationFee(_client, application1.id, false, true); Assert.NotNull(values); Assert.True(values.ContainsKey("trnApproved")); Assert.Equal("0", values["trnApproved"]); // *** // logout and verify we are logged out await Logout(); await GetCurrentUserIsUnauthorized(); // register and login as a second user var loginUser2 = randomNewUserName("NewSecUser2", 6); var businessName2 = randomNewUserName(loginUser2, 6); var strId2 = await LoginAndRegisterAsNewUser(loginUser2, businessName2); ViewModels.User user2 = await GetCurrentUser(); Assert.Equal(user2.name, loginUser2 + " TestUser"); Assert.Equal(user2.businessname, businessName2 + " TestBusiness"); ViewModels.Account account2 = await GetAccountForCurrentUser(); Assert.NotEqual(account1.id, account2.id); Assert.Equal(user2.accountid, account2.id); // *** as user 2, try to access license application invoices of account 1 tmp = await SecurityHelper.GetLicenceApplication(_client, application1.id, false); Assert.Null(tmp); // access invoices and try to pay values = await SecurityHelper.PayLicenceApplicationFee(_client, application1.id, false, false); Assert.Null(values); // *** // logout and cleanup second test user await LogoutAndCleanupTestUser(strId2); await GetCurrentUserIsUnauthorized(); // login again as the same user as above ^^^ await Login(loginUser1, businessName1); user1 = await GetCurrentUser(); Assert.Equal(user1.name, loginUser1 + " TestUser"); Assert.Equal(user1.businessname, businessName1 + " TestBusiness"); account1 = await GetAccountForCurrentUser(); // TODO can't delete once invoices are created // logout and cleanup (deletes the account and contact created above ^^^) await Logout(); await GetCurrentUserIsUnauthorized(); }
//[Fact] public async System.Threading.Tasks.Task UserCantAccessAnotherUsersApplicationAttachments() { // verify (before we log in) that we are not logged in await GetCurrentUserIsUnauthorized(); // register as a new user (creates an account and contact) var loginUser1 = randomNewUserName("NewSecUser1", 6); var businessName1 = randomNewUserName(loginUser1, 6); var strId1 = await LoginAndRegisterAsNewUser(loginUser1, businessName1); // verify the current user represents our new user ViewModels.User user1 = await GetCurrentUser(); Assert.Equal(user1.name, loginUser1 + " TestUser"); Assert.Equal(user1.businessname, businessName1 + " TestBusiness"); // fetch our current account ViewModels.Account account1 = await GetAccountForCurrentUser(); ViewModels.AdoxioLegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client); Assert.Equal(user1.accountid, account1.id); // *** create some license applications ViewModels.AdoxioApplication application1 = await SecurityHelper.CreateLicenceApplication(_client, account1); Assert.NotNull(application1); var tmp = await SecurityHelper.GetLicenceApplication(_client, application1.id, true); Assert.NotNull(tmp); // add an attachment to the application string file1 = await SecurityHelper.UploadFileToApplication(_client, application1.id, "TestAppFileSecurity"); List <ViewModels.FileSystemItem> file1s = await SecurityHelper.GetFileListForApplication(_client, application1.id, "TestAppFileSecurity", true); Assert.NotNull(file1s); Assert.Single(file1s); //string _data1 = await SecurityHelper.DownloadFileForApplication(_client, application1.id, file1s[0].id, true); // *** // logout and verify we are logged out await Logout(); await GetCurrentUserIsUnauthorized(); // register and login as a second user var loginUser2 = randomNewUserName("NewSecUser2", 6); var businessName2 = randomNewUserName(loginUser2, 6); var strId2 = await LoginAndRegisterAsNewUser(loginUser2, businessName2); ViewModels.User user2 = await GetCurrentUser(); Assert.Equal(user2.name, loginUser2 + " TestUser"); Assert.Equal(user2.businessname, businessName2 + " TestBusiness"); ViewModels.Account account2 = await GetAccountForCurrentUser(); Assert.NotEqual(account1.id, account2.id); Assert.Equal(user2.accountid, account2.id); // *** as user 2, try to access license applications of account 1 tmp = await SecurityHelper.GetLicenceApplication(_client, application1.id, false); Assert.Null(tmp); // test access to the application's attachment List <ViewModels.FileSystemItem> file2s = await SecurityHelper.GetFileListForApplication(_client, application1.id, "TestFileSecurity", false); Assert.Null(file2s); //string _data2 = await SecurityHelper.DownloadFileForApplication(_client, application1.id, file1s[0].id, true); // *** // logout and cleanup second test user await LogoutAndCleanupTestUser(strId2); await GetCurrentUserIsUnauthorized(); // login again as the same user as above ^^^ await Login(loginUser1, businessName1); user1 = await GetCurrentUser(); Assert.Equal(user1.name, loginUser1 + " TestUser"); Assert.Equal(user1.businessname, businessName1 + " TestBusiness"); account1 = await GetAccountForCurrentUser(); // *** delete license applications of account 1 // delete the application's attachments //await SecurityHelper.DeleteFileForApplication(_client, application1.id, file1s[0].id); await SecurityHelper.DeleteLicenceApplication(_client, application1.id); // *** // logout and cleanup (deletes the account and contact created above ^^^) await LogoutAndCleanupTestUser(strId1); await GetCurrentUserIsUnauthorized(); }
public async System.Threading.Tasks.Task PaymentSubmitReturnsValidRedirectUrlAndCanBePaid() { if (_client.BaseAddress.ToString() != "http://localhost/") { return; } string service = "payment"; // first confirm we are not logged in await GetCurrentUserIsUnauthorized(); // login as default and get account for current user string loginUser = randomNewUserName("TestPayUser_", 6); var strId = await LoginAndRegisterAsNewUser(loginUser); ViewModels.User user = await GetCurrentUser(); ViewModels.Account currentAccount = await GetAccountForCurrentUser(); // create an application to test with (need a valid id) var request = new HttpRequestMessage(HttpMethod.Post, "/api/adoxioapplication"); ViewModels.AdoxioApplication viewmodel_application = new ViewModels.AdoxioApplication() { licenseType = "Cannabis Retail Store", //*Mandatory field **This is an entity** E.g.Cannabis Retail Store applicantType = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation, //*Mandatory (label=business type) registeredEstablishment = ViewModels.GeneralYesNo.No, //*Mandatory (Yes=1, No=0) //,name = initialName //,applyingPerson = "Applying Person" //contact applicant = currentAccount, //account //,jobNumber = "123" establishmentName = "Not a Dispensary", establishmentAddress = "123 Any Street, Victoria, BC, V1X 1X1", establishmentaddressstreet = "123 Any Street", establishmentaddresscity = "Victoria, BC", establishmentaddresspostalcode = "V1X 1X1", applicationStatus = AdoxioApplicationStatusCodes.InProgress }; var jsonString = JsonConvert.SerializeObject(viewmodel_application); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); ViewModels.AdoxioApplication responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); //Assert.Equal("Applying Person", responseViewModel.applyingPerson); Assert.Equal("Not a Dispensary", responseViewModel.establishmentName); Assert.Equal("Victoria, BC", responseViewModel.establishmentaddresscity); Assert.Equal("V1X 1X1", responseViewModel.establishmentaddresspostalcode); string id = responseViewModel.id; request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/submit/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); Dictionary <string, string> values = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); Assert.True(values.ContainsKey("url")); string ordernum = values["url"].Substring(values["url"].IndexOf("trnOrderNumber=") + 15, 10); Assert.Equal(10, ordernum.Length); string actual_url = "https://web.na.bambora.com/scripts/Payment/Payment.asp?merchant_id=336660000&trnType=P&trnOrderNumber=" + ordernum + "&ref1=http://localhost:5000/cannabislicensing/payment-confirmation&ref3=" + id + "&trnAmount=7500.00&hashExpiry="; Assert.True(values["url"].Length > actual_url.Length); Assert.Equal(actual_url, values["url"].Substring(0, actual_url.Length)); // get a response request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/verify/" + id + "/APPROVE"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); json = await response.Content.ReadAsStringAsync(); values = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); Assert.True(values.ContainsKey("query_url")); Assert.True(values.ContainsKey("trnApproved")); Assert.Equal("1", values["trnApproved"]); // fetch updated application request = new HttpRequestMessage(HttpMethod.Get, "/api/adoxioapplication/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); string invoiceId = responseViewModel.adoxioInvoiceId; Assert.Equal(ViewModels.GeneralYesNo.Yes, responseViewModel.adoxioInvoiceTrigger); // delete invoice - note we can't delete an invoice created by Dynamics //request = new HttpRequestMessage(HttpMethod.Post, "/api/invoice/" + invoiceId + "/delete"); //response = await _client.SendAsync(request); //string responseText = await response.Content.ReadAsStringAsync(); //response.EnsureSuccessStatusCode(); // delete application request = new HttpRequestMessage(HttpMethod.Post, "/api/adoxioapplication/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/adoxioapplication/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // logout and cleanup (deletes the account and contact created above ^^^) // note we can't delete the account due to the dependency on the invoice created by Dynamics await Logout(); // LogoutAndCleanupTestUser(strId); }
public async System.Threading.Tasks.Task TestUserCanAccessApplicationForTheirAccount() { string initialName = randomNewUserName("Application Shared ", 6); string service = "adoxioapplication"; // login as default and get account for current user string loginUser1 = randomNewUserName("TestAppUser", 6); string loginAccount = randomNewUserName(loginUser1, 6); string loginUser2 = loginUser1 + "-2"; loginUser1 = loginUser1 + "-1"; var strId1 = await LoginAndRegisterAsNewUser(loginUser1, loginAccount); ViewModels.User user1 = await GetCurrentUser(); ViewModels.Account currentAccount1 = await GetAccountForCurrentUser(); // C - Create var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service); ViewModels.AdoxioApplication viewmodel_application = new ViewModels.AdoxioApplication() { name = initialName, applyingPerson = "Applying Person", applicant = currentAccount1, jobNumber = "123", licenseType = "Cannabis", establishmentName = "Shared Retail Store", establishmentAddress = "666 Any Street, Victoria, BC, V1X 1X1", establishmentaddressstreet = "666 Any Street", establishmentaddresscity = "Victoria, BC", establishmentaddresspostalcode = "V1X 1X1", applicationStatus = "845280000" }; var jsonString = JsonConvert.SerializeObject(viewmodel_application); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); ViewModels.AdoxioApplication responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); // name should match. Assert.Equal("Shared Retail Store", responseViewModel.establishmentName); Assert.Equal("Victoria, BC", responseViewModel.establishmentaddresscity); Assert.Equal("V1X 1X1", responseViewModel.establishmentaddresspostalcode); Guid id = new Guid(responseViewModel.id); // R - Read request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); Assert.Equal(currentAccount1.id, responseViewModel.applicant.id); await Logout(); // register and login as a second user var strId2 = await LoginAndRegisterAsNewUser(loginUser2, loginAccount); ViewModels.User user2 = await GetCurrentUser(); ViewModels.Account currentAccount2 = await GetAccountForCurrentUser(); // same account as user 1 Assert.Equal(currentAccount2.id, currentAccount1.id); // R - Read (should be able to access by user) request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // logout and cleanup (deletes the account and contact created above ^^^) await LogoutAndCleanupTestUser(strId2); // log back in as first user await Login(loginUser1); // R - Read - still has access to application request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); Assert.Equal(currentAccount1.id, responseViewModel.applicant.id); // D - Delete request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // logout and cleanup (deletes the account and contact created above ^^^) await LogoutAndCleanupTestUser(strId1); //await Logout(); }
public async static Task <AdoxioApplication> ToViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication, IDynamicsClient dynamicsClient) { AdoxioApplication adoxioApplicationVM = new ViewModels.AdoxioApplication(); // id if (dynamicsApplication.AdoxioApplicationid != null) { adoxioApplicationVM.id = dynamicsApplication.AdoxioApplicationid.ToString(); } //get name adoxioApplicationVM.name = dynamicsApplication.AdoxioName; //get applying person from Contact entity if (dynamicsApplication._adoxioApplyingpersonValue != null) { Guid applyingPersonId = Guid.Parse(dynamicsApplication._adoxioApplyingpersonValue); var contact = await dynamicsClient.GetContactById(applyingPersonId); adoxioApplicationVM.applyingPerson = contact.Fullname; } if (dynamicsApplication._adoxioApplicantValue != null) { var applicant = await dynamicsClient.GetAccountById(Guid.Parse(dynamicsApplication._adoxioApplicantValue)); adoxioApplicationVM.applicant = applicant.ToViewModel(); } //get job number adoxioApplicationVM.jobNumber = dynamicsApplication.AdoxioJobnumber; //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); adoxioApplicationVM.licenseType = adoxio_licencetype.AdoxioName; } //get establishment name and address adoxioApplicationVM.establishmentName = dynamicsApplication.AdoxioEstablishmentpropsedname; adoxioApplicationVM.establishmentaddressstreet = dynamicsApplication.AdoxioEstablishmentaddressstreet; adoxioApplicationVM.establishmentaddresscity = dynamicsApplication.AdoxioEstablishmentaddresscity; adoxioApplicationVM.establishmentaddresspostalcode = dynamicsApplication.AdoxioEstablishmentaddresspostalcode; adoxioApplicationVM.establishmentAddress = dynamicsApplication.AdoxioEstablishmentaddressstreet + ", " + dynamicsApplication.AdoxioEstablishmentaddresscity + " " + dynamicsApplication.AdoxioEstablishmentaddresspostalcode; //get application status adoxioApplicationVM.applicationStatus = (AdoxioApplicationStatusCodes)dynamicsApplication.Statuscode; // set a couple of read-only flags to indicate status adoxioApplicationVM.isPaid = (dynamicsApplication.AdoxioPaymentrecieved != null && (bool)dynamicsApplication.AdoxioPaymentrecieved); //get parcel id adoxioApplicationVM.establishmentparcelid = dynamicsApplication.AdoxioEstablishmentparcelid; //get additional property info adoxioApplicationVM.additionalpropertyinformation = dynamicsApplication.AdoxioAdditionalpropertyinformation; //get payment info if (dynamicsApplication.AdoxioInvoicetrigger == 1) { adoxioApplicationVM.adoxioInvoiceTrigger = GeneralYesNo.Yes; adoxioApplicationVM.isSubmitted = true; } else { adoxioApplicationVM.adoxioInvoiceTrigger = GeneralYesNo.No; adoxioApplicationVM.isSubmitted = false; } adoxioApplicationVM.adoxioInvoiceId = dynamicsApplication._adoxioInvoiceValue; //TODO set in autorest adoxioApplicationVM.paymentreceiveddate = dynamicsApplication.AdoxioPaymentreceiveddate; //DateTime.Now; adoxioApplicationVM.prevPaymentFailed = (dynamicsApplication._adoxioInvoiceValue != null) && (!adoxioApplicationVM.isSubmitted); //get declarations adoxioApplicationVM.authorizedtosubmit = dynamicsApplication.AdoxioAuthorizedtosubmit; adoxioApplicationVM.signatureagreement = dynamicsApplication.AdoxioSignatureagreement; //get contact details adoxioApplicationVM.contactpersonfirstname = dynamicsApplication.AdoxioContactpersonfirstname; adoxioApplicationVM.contactpersonlastname = dynamicsApplication.AdoxioContactpersonlastname; adoxioApplicationVM.contactpersonrole = dynamicsApplication.AdoxioRole; adoxioApplicationVM.contactpersonemail = dynamicsApplication.AdoxioEmail; adoxioApplicationVM.contactpersonphone = dynamicsApplication.AdoxioContactpersonphone; adoxioApplicationVM.modifiedOn = dynamicsApplication.Modifiedon; //get record audit info adoxioApplicationVM.createdon = dynamicsApplication.Createdon; adoxioApplicationVM.modifiedon = dynamicsApplication.Modifiedon; return(adoxioApplicationVM); }
public async Task <IActionResult> GetPaymentUrl(string id) { _logger.LogError("Called GetPaymentUrl(" + id + ")"); // get the application and confirm access (call parse to ensure we are getting a valid id) Guid applicationId = Guid.Parse(id); MicrosoftDynamicsCRMadoxioApplication adoxioApplication = await GetDynamicsApplication(id); if (adoxioApplication == null) { return(NotFound()); } // set the application invoice trigger to create an invoice ViewModels.AdoxioApplication vm = await adoxioApplication.ToViewModel(_dynamicsClient); MicrosoftDynamicsCRMadoxioApplication adoxioApplication2 = new MicrosoftDynamicsCRMadoxioApplication(); adoxioApplication2.CopyValues(vm); // this is the money - setting this flag to "Y" triggers a dynamics workflow that creates an invoice adoxioApplication2.AdoxioInvoicetrigger = (int?)ViewModels.GeneralYesNo.Yes; _dynamicsClient.Applications.Update(id, adoxioApplication2); adoxioApplication2 = await GetDynamicsApplication(id); // now load the invoice for this application to get the pricing string invoiceId = adoxioApplication2._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 = adoxioApplication2._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>(); redirectUrl["url"] = _bcep.GeneratePaymentRedirectUrl(ordernum, id, String.Format("{0:0.00}", orderamt)); _logger.LogError(">>>>>" + redirectUrl["url"]); return(Json(redirectUrl)); }
public async Task <IActionResult> VerifyPaymentStatus(string id) { MicrosoftDynamicsCRMadoxioApplication adoxioApplication = await GetDynamicsApplication(id); if (adoxioApplication == null) { return(NotFound()); } // load the invoice for this application string invoiceId = adoxioApplication._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, id); 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.AdoxioApplication vma = await adoxioApplication.ToViewModel(_dynamicsClient); MicrosoftDynamicsCRMadoxioApplication adoxioApplication2 = new MicrosoftDynamicsCRMadoxioApplication(); adoxioApplication2.CopyValues(vma); // 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 adoxioApplication2.AdoxioPaymentrecieved = (bool?)true; adoxioApplication2.AdoxioPaymentmethod = (int?)Adoxio_paymentmethods.CC; adoxioApplication2.AdoxioAppchecklistpaymentreceived = (int?)ViewModels.GeneralYesNo.Yes; _dynamicsClient.Applications.Update(id, adoxioApplication2); adoxioApplication2 = await GetDynamicsApplication(id); } // 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 adoxioApplication2.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.Applications.Update(id, adoxioApplication2); adoxioApplication2 = await GetDynamicsApplication(id); } } 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> CreateApplication([FromBody] ViewModels.AdoxioApplication item) { // for association with current user string userJson = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson); int count = GetSubmittedCountByApplicant(userSettings.AccountId); if (count >= 8) { return(BadRequest("8 applications have already been submitted. Can not create more")); } MicrosoftDynamicsCRMadoxioApplication adoxioApplication = new MicrosoftDynamicsCRMadoxioApplication(); // copy received values to Dynamics Application adoxioApplication.CopyValues(item); adoxioApplication.AdoxioApplicanttype = (int?)item.applicantType; try { var adoxioLicencetype = _dynamicsClient.GetAdoxioLicencetypeByName(item.licenseType); // set license type relationship adoxioApplication.AdoxioLicenceTypeODataBind = _dynamicsClient.GetEntityURI("adoxio_licencetypes", adoxioLicencetype.AdoxioLicencetypeid); adoxioApplication.AdoxioApplicantODataBind = _dynamicsClient.GetEntityURI("accounts", userSettings.AccountId); adoxioApplication = _dynamicsClient.Applications.Create(adoxioApplication); } catch (OdataerrorException odee) { string applicationId = _dynamicsClient.GetCreatedRecord(odee, null); if (!string.IsNullOrEmpty(applicationId) && Guid.TryParse(applicationId, out Guid applicationGuid)) { adoxioApplication = await _dynamicsClient.GetApplicationById(applicationGuid); } else { _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); } } // in case the job number is not there, try getting the record from the server. if (adoxioApplication.AdoxioJobnumber == null) { _logger.LogError("AdoxioJobnumber is null, fetching record again."); Guid id = Guid.Parse(adoxioApplication.AdoxioApplicationid); adoxioApplication = await _dynamicsClient.GetApplicationById(id); } if (adoxioApplication.AdoxioJobnumber == null) { _logger.LogError("Unable to get the Job Number for the Application."); throw new Exception("Error creating Licence Application."); } // create a SharePointDocumentLocation link string folderName = GetApplicationFolderName(adoxioApplication); string name = adoxioApplication.AdoxioJobnumber + " Files"; // Create the folder bool folderExists = await _sharePointFileManager.FolderExists(ApplicationDocumentUrlTitle, folderName); if (!folderExists) { try { var folder = await _sharePointFileManager.CreateFolder(ApplicationDocumentUrlTitle, folderName); } catch (Exception e) { _logger.LogError("Error creating Sharepoint Folder"); _logger.LogError($"List is: {ApplicationDocumentUrlTitle}"); _logger.LogError($"FolderName is: {folderName}"); throw e; } } // Create the SharePointDocumentLocation entity MicrosoftDynamicsCRMsharepointdocumentlocation mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation() { Relativeurl = folderName, Description = "Application Files", Name = name }; try { mdcsdl = _dynamicsClient.SharepointDocumentLocations.Create(mdcsdl); } catch (OdataerrorException odee) { string mdcsdlId = _dynamicsClient.GetCreatedRecord(odee, null); if (!string.IsNullOrEmpty(mdcsdlId)) { mdcsdl.Sharepointdocumentlocationid = mdcsdlId; } else { _logger.LogError("Error creating SharepointDocumentLocation"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); mdcsdl = null; } } if (mdcsdl != null) { // add a regardingobjectid. string applicationReference = _dynamicsClient.GetEntityURI("adoxio_applications", adoxioApplication.AdoxioApplicationid); var patchSharePointDocumentLocation = new MicrosoftDynamicsCRMsharepointdocumentlocation(); patchSharePointDocumentLocation.RegardingobjectidAdoxioApplicationODataBind = applicationReference; // set the parent document library. string parentDocumentLibraryReference = GetDocumentLocationReferenceByRelativeURL("adoxio_application"); patchSharePointDocumentLocation.ParentsiteorlocationSharepointdocumentlocationODataBind = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference); try { _dynamicsClient.SharepointDocumentLocations.Update(mdcsdl.Sharepointdocumentlocationid, patchSharePointDocumentLocation); } catch (OdataerrorException odee) { _logger.LogError("Error adding reference SharepointDocumentLocation to application"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } string sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", mdcsdl.Sharepointdocumentlocationid); // update the sharePointLocationData. Odataid oDataId = new Odataid() { OdataidProperty = sharePointLocationData }; try { _dynamicsClient.Applications.AddReference(adoxioApplication.AdoxioApplicationid, "adoxio_application_SharePointDocumentLocations", oDataId); } catch (OdataerrorException odee) { _logger.LogError("Error adding reference to SharepointDocumentLocation"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } } return(Json(await adoxioApplication.ToViewModel(_dynamicsClient))); }
public async System.Threading.Tasks.Task TestFileListing() { string initialName = randomNewUserName("First InitialName", 6); string changedName = randomNewUserName("First ChangedName", 6); string service = "adoxioapplication"; // Login as default user var loginUser = randomNewUserName("NewLoginUser", 6); var strId = await LoginAndRegisterAsNewUser(loginUser); ViewModels.User user = await GetCurrentUser(); ViewModels.Account currentAccount = await GetAccountForCurrentUser(); // C - Create var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service); ViewModels.AdoxioApplication viewmodel_application = new ViewModels.AdoxioApplication() { licenseType = "Cannabis Retail Store" //*Mandatory field **This is an entity** E.g.Cannabis Retail Store , applicantType = ViewModels.Adoxio_applicanttypecodes.PrivateCorporation //*Mandatory (label=business type) , registeredEstablishment = ViewModels.GeneralYesNo.No //*Mandatory (Yes=1, No=0) //,name = initialName //,applyingPerson = "Applying Person" //contact , applicant = currentAccount //account //,jobNumber = "123" , establishmentName = "Not a Dispensary" , establishmentAddress = "123 Any Street, Victoria, BC, V1X 1X1" , establishmentaddressstreet = "123 Any Street" , establishmentaddresscity = "Victoria, BC" , establishmentaddresspostalcode = "V1X 1X1" //,applicationStatus = "0" }; var jsonString = JsonConvert.SerializeObject(viewmodel_application); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); jsonString = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); // parse as JSON. ViewModels.AdoxioApplication responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); //Assert.Equal("Applying Person", responseViewModel.applyingPerson); Assert.Equal("Not a Dispensary", responseViewModel.establishmentName); Assert.Equal("Victoria, BC", responseViewModel.establishmentaddresscity); Assert.Equal("V1X 1X1", responseViewModel.establishmentaddresspostalcode); Guid id = new Guid(responseViewModel.id); // Attach a file string testData = "This is just a test."; byte[] bytes = Encoding.ASCII.GetBytes(testData); string documentType = "Test Document Type"; // Create random filename var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var stringChars = new char[9]; var random = new Random(); for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } var randomString = new String(stringChars); string filename = randomString + ".txt"; MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----TestBoundary"); var fileContent = new MultipartContent { new ByteArrayContent(bytes) }; fileContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data"); fileContent.Headers.ContentDisposition.Name = "File"; fileContent.Headers.ContentDisposition.FileName = filename; multiPartContent.Add(fileContent); multiPartContent.Add(new StringContent(documentType), "documentType"); // form input string accountId = user.accountid; // create a new request object for the upload, as we will be using multipart form submission. var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/attachments"); requestMessage.Content = multiPartContent; var uploadResponse = await _client.SendAsync(requestMessage); uploadResponse.EnsureSuccessStatusCode(); // Cleanup request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); await LogoutAndCleanupTestUser(strId); }
public async System.Threading.Tasks.Task TestCRUD() { string initialName = randomNewUserName("Application Initial Name ", 6); string changedName = randomNewUserName("Application Changed Name ", 6); string service = "adoxioapplication"; // login as default and get account for current user string loginUser = randomNewUserName("TestAppUser_", 6); var strId = await LoginAndRegisterAsNewUser(loginUser); ViewModels.User user = await GetCurrentUser(); ViewModels.Account currentAccount = await GetAccountForCurrentUser(); // C - Create var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service); ViewModels.AdoxioApplication viewmodel_application = new ViewModels.AdoxioApplication() { licenseType = "Cannabis Retail Store" //*Mandatory field **This is an entity** E.g.Cannabis Retail Store , applicantType = ViewModels.Adoxio_applicanttypecodes.PrivateCorporation //*Mandatory (label=business type) , registeredEstablishment = ViewModels.GeneralYesNo.No //*Mandatory (Yes=1, No=0) //,name = initialName //,applyingPerson = "Applying Person" //contact , applicant = currentAccount //account //,jobNumber = "123" , establishmentName = "Not a Dispensary" , establishmentAddress = "123 Any Street, Victoria, BC, V1X 1X1" , establishmentaddressstreet = "123 Any Street" , establishmentaddresscity = "Victoria, BC" , establishmentaddresspostalcode = "V1X 1X1" //,applicationStatus = "0" }; var jsonString = JsonConvert.SerializeObject(viewmodel_application); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); ViewModels.AdoxioApplication responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); //Assert.Equal("Applying Person", responseViewModel.applyingPerson); Assert.Equal("Not a Dispensary", responseViewModel.establishmentName); Assert.Equal("Victoria, BC", responseViewModel.establishmentaddresscity); Assert.Equal("V1X 1X1", responseViewModel.establishmentaddresspostalcode); Guid id = new Guid(responseViewModel.id); //return; // R - Read request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); Assert.Equal("Not a Dispensary", responseViewModel.establishmentName); Assert.True(responseViewModel.applicant != null); Assert.Equal(currentAccount.id, responseViewModel.applicant.id); // U - Update viewmodel_application.establishmentName = changedName; viewmodel_application.id = id.ToString(); request = new HttpRequestMessage(HttpMethod.Put, "/api/" + service + "/" + id) { Content = new StringContent(JsonConvert.SerializeObject(viewmodel_application), Encoding.UTF8, "application/json") }; response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // verify that the update persisted. request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); Assert.Equal(changedName, responseViewModel.establishmentName); // D - Delete request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // second delete should return a 404. request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete"); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // logout and cleanup (deletes the account and contact created above ^^^) await LogoutAndCleanupTestUser(strId); }
public async System.Threading.Tasks.Task CantAccessApplicationOfDifferentCompany() { string service = "payment"; // first confirm we are not logged in await GetCurrentUserIsUnauthorized(); // login as default and get account for current user string loginUser = randomNewUserName("TestPayUser_", 6); string loginUser1 = loginUser + "_1"; var strId1 = await LoginAndRegisterAsNewUser(loginUser1); ViewModels.User user1 = await GetCurrentUser(); ViewModels.Account currentAccount1 = await GetAccountForCurrentUser(); // create an application to test with (need a valid id) var request = new HttpRequestMessage(HttpMethod.Post, "/api/adoxioapplication"); ViewModels.AdoxioApplication viewmodel_application = new ViewModels.AdoxioApplication() { name = "Test Application Name", applyingPerson = "Applying Person", //contact applicant = currentAccount1, //account licenseType = "Cannabis Retail Store", //*Mandatory field **This is an entity** E.g.Cannabis Retail Store applicantType = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation, //*Mandatory (label=business type) jobNumber = "123", registeredEstablishment = ViewModels.GeneralYesNo.No, //*Mandatory (Yes=1, No=0) establishmentName = "Not a Dispensary", establishmentAddress = "123 Any Street, Victoria, BC, V1X 1X1", establishmentaddressstreet = "123 Any Street", establishmentaddresscity = "Victoria, BC", establishmentaddresspostalcode = "V1X 1X1", applicationStatus = AdoxioApplicationStatusCodes.InProgress }; var jsonString = JsonConvert.SerializeObject(viewmodel_application); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); ViewModels.AdoxioApplication responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); //Assert.Equal("Applying Person", responseViewModel.applyingPerson); Assert.Equal("Not a Dispensary", responseViewModel.establishmentName); Assert.Equal("Victoria, BC", responseViewModel.establishmentaddresscity); Assert.Equal("V1X 1X1", responseViewModel.establishmentaddresspostalcode); string id = responseViewModel.id; request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/submit/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); Dictionary <string, string> values = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); Assert.True(values.ContainsKey("url")); // logout so we can test as another user await Logout(); // login as a second user and business string loginUser2 = loginUser + "_2"; var strId2 = await LoginAndRegisterAsNewUser(loginUser2); // try to access user 1's application request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/submit/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/verify/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // logout and cleanup (deletes the account and contact created above ^^^) await LogoutAndCleanupTestUser(strId2); // logout and cleanup (deletes the account and contact created above ^^^) await Login(loginUser1); // delete application request = new HttpRequestMessage(HttpMethod.Post, "/api/adoxioapplication/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/adoxioapplication/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // note we can't delete the account due to the dependency on the invoice created by Dynamics await Logout(); }
public async System.Threading.Tasks.Task GetAllLicensesTest() { string initialName = randomNewUserName("License Test ", 6); string service = "adoxioapplication"; // login as default and get account for current user string loginUser1 = randomNewUserName("TestAppUser", 6); string loginAccount = randomNewUserName(loginUser1, 6); loginUser1 = loginUser1 + "-1"; var strId1 = await LoginAndRegisterAsNewUser(loginUser1, loginAccount); ViewModels.User user1 = await GetCurrentUser(); ViewModels.Account currentAccount1 = await GetAccountForCurrentUser(); var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service); ViewModels.AdoxioApplication viewmodel_application = new ViewModels.AdoxioApplication() { name = initialName, applyingPerson = "Applying Person", applicant = currentAccount1, applicantType = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation, jobNumber = "123", licenseType = "Cannabis Retail Store", establishmentName = "Shared Retail Store", establishmentAddress = "666 Any Street, Victoria, BC, V1X 1X1", establishmentaddressstreet = "666 Any Street", establishmentaddresscity = "Victoria, BC", establishmentaddresspostalcode = "V1X 1X1", applicationStatus = AdoxioApplicationStatusCodes.Approved }; var jsonString = JsonConvert.SerializeObject(viewmodel_application); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); ViewModels.AdoxioApplication responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); Assert.Equal("Shared Retail Store", responseViewModel.establishmentName); Assert.Equal("Victoria, BC", responseViewModel.establishmentaddresscity); Assert.Equal("V1X 1X1", responseViewModel.establishmentaddresspostalcode); Guid id = new Guid(responseViewModel.id); request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); Assert.Equal(currentAccount1.id, responseViewModel.applicant.id); service = "adoxiolicense"; request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service); response = await _client.SendAsync(request); jsonString = await response.Content.ReadAsStringAsync(); var responseViewModelList = JsonConvert.DeserializeObject <List <AdoxioLicense> >(jsonString); response.EnsureSuccessStatusCode(); // TODO: License controller is not set up yet. Response passes, however, nothing is returned. await LogoutAndCleanupTestUser(strId1); }
public async System.Threading.Tasks.Task PaymentSubmitDeclinedAndThenResubitApprovedWorks() { string service = "payment"; // first confirm we are not logged in await GetCurrentUserIsUnauthorized(); // login as default and get account for current user string loginUser = randomNewUserName("TestPayUser_", 6); var strId = await LoginAndRegisterAsNewUser(loginUser); ViewModels.User user = await GetCurrentUser(); ViewModels.Account currentAccount = await GetAccountForCurrentUser(); // create an application to test with (need a valid id) var request = new HttpRequestMessage(HttpMethod.Post, "/api/adoxioapplication"); ViewModels.AdoxioApplication viewmodel_application = new ViewModels.AdoxioApplication() { licenseType = "Cannabis Retail Store", //*Mandatory field **This is an entity** E.g.Cannabis Retail Store applicantType = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation, //*Mandatory (label=business type) registeredEstablishment = ViewModels.GeneralYesNo.No, //*Mandatory (Yes=1, No=0) //,name = initialName //,applyingPerson = "Applying Person" //contact applicant = currentAccount, //account //,jobNumber = "123" establishmentName = "Not a Dispensary", establishmentAddress = "123 Any Street, Victoria, BC, V1X 1X1", establishmentaddressstreet = "123 Any Street", establishmentaddresscity = "Victoria, BC", establishmentaddresspostalcode = "V1X 1X1" //,applicationStatus = "0" }; var jsonString = JsonConvert.SerializeObject(viewmodel_application); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); ViewModels.AdoxioApplication responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); Assert.Equal("Not a Dispensary", responseViewModel.establishmentName); Assert.Equal("Victoria, BC", responseViewModel.establishmentaddresscity); Assert.Equal("V1X 1X1", responseViewModel.establishmentaddresspostalcode); string id = responseViewModel.id; request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/submit/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); Dictionary <string, string> values = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); Assert.True(values.ContainsKey("url")); string ordernum = values["url"].Substring(values["url"].IndexOf("trnOrderNumber=") + 15, 10); Assert.Equal(10, ordernum.Length); // get a response - ask for a DECLINE request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/verify/" + id + "/DECLINE"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); json = await response.Content.ReadAsStringAsync(); values = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); Assert.True(values.ContainsKey("query_url")); Assert.True(values.ContainsKey("trnApproved")); Assert.Equal("0", values["trnApproved"]); // fetch updated application request = new HttpRequestMessage(HttpMethod.Get, "/api/adoxioapplication/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); string invoiceId = responseViewModel.adoxioInvoiceId; // check application status Assert.Equal(ViewModels.GeneralYesNo.No, responseViewModel.adoxioInvoiceTrigger); // submit a second time to get it paid request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/submit/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); json = await response.Content.ReadAsStringAsync(); values = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); Assert.True(values.ContainsKey("url")); // we should get a different order number string ordernum2 = values["url"].Substring(values["url"].IndexOf("trnOrderNumber=") + 15, 10); Assert.Equal(10, ordernum2.Length); Assert.NotEqual(ordernum2, ordernum); // get a response request = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/verify/" + id + "/APPROVE"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); json = await response.Content.ReadAsStringAsync(); values = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); Assert.True(values.ContainsKey("query_url")); Assert.True(values.ContainsKey("trnApproved")); Assert.Equal("1", values["trnApproved"]); // fetch updated application request = new HttpRequestMessage(HttpMethod.Get, "/api/adoxioapplication/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); jsonString = await response.Content.ReadAsStringAsync(); responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString); string invoiceId2 = responseViewModel.adoxioInvoiceId; Assert.NotEqual(invoiceId2, invoiceId); Assert.Equal(ViewModels.GeneralYesNo.Yes, responseViewModel.adoxioInvoiceTrigger); // delete invoice - note we can't delete an invoice created by Dynamics //request = new HttpRequestMessage(HttpMethod.Post, "/api/invoice/" + invoiceId + "/delete"); //response = await _client.SendAsync(request); //string responseText = await response.Content.ReadAsStringAsync(); //response.EnsureSuccessStatusCode(); // delete application request = new HttpRequestMessage(HttpMethod.Post, "/api/adoxioapplication/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/adoxioapplication/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // logout and cleanup (deletes the account and contact created above ^^^) // note we can't delete the account due to the dependency on the invoice created by Dynamics await Logout(); // LogoutAndCleanupTestUser(strId); }