public async Task <IActionResult> GetInvoice(string id)
        {
            ViewModels.Invoice result = null;
            // query the Dynamics system to get the invoice record.
            if (string.IsNullOrEmpty(id))
            {
                return(new NotFoundResult());
            }
            else
            {
                // get the current user.
                string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
                UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

                Guid adoxio_legalentityid           = new Guid(id);
                MicrosoftDynamicsCRMinvoice invoice = await _dynamicsClient.GetInvoiceById(adoxio_legalentityid);

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

                // setup the related account.
                if (invoice._accountidValue != null)
                {
                    Guid accountId = Guid.Parse(invoice._accountidValue);
                    invoice.CustomeridAccount = await _dynamicsClient.GetAccountById(accountId);
                }

                result = invoice.ToViewModel();
            }

            return(Json(result));
        }
        public async Task <IActionResult> GetInvoice(string id)
        {
            if (TestUtility.InUnitTestMode())
            {
                ViewModels.Invoice result = null;
                // query the Dynamics system to get the invoice record.
                if (string.IsNullOrEmpty(id))
                {
                    return(new NotFoundResult());
                }

                // get the current user.
                UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

                Guid adoxio_legalentityid           = new Guid(id);
                MicrosoftDynamicsCRMinvoice invoice = await _dynamicsClient.GetInvoiceById(adoxio_legalentityid);

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

                // setup the related account.
                if (invoice._accountidValue != null)
                {
                    Guid accountId = Guid.Parse(invoice._accountidValue);
                    invoice.CustomeridAccount = await _dynamicsClient.GetAccountByIdAsync(accountId);
                }

                result = invoice.ToViewModel();

                return(new JsonResult(result));
            }
            return(new NotFoundResult());
        }
        public async Task <IActionResult> UpdateInvoice([FromBody] ViewModels.Invoice item, string id)
        {
            if (id != item.id)
            {
                return(BadRequest());
            }

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

            MicrosoftDynamicsCRMinvoice invoice = await _dynamicsClient.GetInvoiceById(adoxio_legalentityid);

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

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

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

            await _dynamicsClient.Invoices.UpdateAsync(adoxio_legalentityid.ToString(), invoice);

            return(Json(invoice.ToViewModel()));
        }
Example #4
0
        public async Task <IActionResult> CreateInvoice([FromBody] ViewModels.Invoice item)
        {
            if (TestUtility.InUnitTestMode())
            {
                // create a new invoice.
                MicrosoftDynamicsCRMinvoice invoice = new MicrosoftDynamicsCRMinvoice();

                // get the current user.
                string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
                UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);
                // check that the session is setup correctly.
                userSettings.Validate();
                // copy received values to Dynamics LegalEntity
                invoice.CopyValues(item);
                try
                {
                    invoice = await _dynamicsClient.Invoices.CreateAsync(invoice);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError("Error creating invoice");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                    throw new Exception("Unable to create invoice");
                }

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

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

                // patch the record.
                try
                {
                    await _dynamicsClient.Invoices.UpdateAsync(invoice.Invoiceid, patchEntity);

                    // setup the view model.
                    invoice.CustomeridAccount = userAccount;
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError("Error patching invoice");
                    _logger.LogError(odee.Request.RequestUri.ToString());
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                }

                return(Json(invoice.ToViewModel()));
            }
            return(new NotFoundResult());
        }
Example #5
0
 public static void CopyValues(this MicrosoftDynamicsCRMinvoice to, ViewModels.Invoice from)
 {
     to.Invoiceid           = from.id;
     to.Name                = from.name;
     to.Invoicenumber       = from.invoicenumber;
     to.Statecode           = from.statecode;
     to.Statuscode          = from.statuscode;
     to.Totaltax            = from.totaltax;
     to.Totalamount         = from.totalamount;
     to.AdoxioTransactionid = from.transactionId;
 }
        public async Task <IActionResult> CreateInvoice([FromBody] ViewModels.Invoice item)
        {
            if (TestUtility.InUnitTestMode())
            {
                // create a new invoice.
                MicrosoftDynamicsCRMinvoice invoice = new MicrosoftDynamicsCRMinvoice();

                // get the current user.
                UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);
                // check that the session is setup correctly.
                userSettings.Validate();
                // copy received values to Dynamics LegalEntity
                invoice.CopyValues(item);
                try
                {
                    invoice = await _dynamicsClient.Invoices.CreateAsync(invoice);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, "Error creating invoice");
                    throw new Exception("Unable to create invoice");
                }

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

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

                // patch the record.
                try
                {
                    await _dynamicsClient.Invoices.UpdateAsync(invoice.Invoiceid, patchEntity);

                    // setup the view model.
                    invoice.CustomeridAccount = userAccount;
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, "Error patching invoice");
                }

                return(new JsonResult(invoice.ToViewModel()));
            }
            return(new NotFoundResult());
        }
Example #7
0
        public async System.Threading.Tasks.Task TestCRUD()
        {
            string initialName = "InitialName";
            string changedName = "ChangedName";
            string service     = "invoice";

            // first confirm we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register and login as our first user
            var loginUser1 = randomNewUserName("TestInvoiceUser", 6);
            var strId      = await LoginAndRegisterAsNewUser(loginUser1);

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

            ViewModels.Invoice viewmodel_invoice = new ViewModels.Invoice()
            {
                name          = initialName,
                invoicenumber = "12345",
                statecode     = (int?)Adoxio_invoicestates.New,
                statuscode    = (int?)Adoxio_invoicestatuses.New,
                totalamount   = 7500.00
            };

            string jsonString = JsonConvert.SerializeObject(viewmodel_invoice);

            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.Invoice responseViewModel = JsonConvert.DeserializeObject <ViewModels.Invoice>(jsonString);

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

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

            // R - Read

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

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

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

            viewmodel_invoice.id = id.ToString();

            // U - Update
            viewmodel_invoice.name = changedName;

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

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // verify that the update persisted.

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

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

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

            // D - Delete

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

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

            response.EnsureSuccessStatusCode();

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

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

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

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

            await LogoutAndCleanupTestUser(strId);
        }
Example #8
0
        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));
        }