Beispiel #1
0
        private async Task <SapTaskResult> CreateCreditNote(SapSaleOrderInvoiceResponse sapSaleOrderInvoiceResponse, SapTask dequeuedTask, string sapSystem)
        {
            var sapCreditNote = GetMapper(sapSystem).MapToSapCreditNote(sapSaleOrderInvoiceResponse, dequeuedTask.CreditNoteRequest);

            sapCreditNote.BillingSystemId = dequeuedTask.CreditNoteRequest.BillingSystemId;

            var serviceSetting = SapServiceSettings.GetSettings(_sapConfig, sapSystem);
            var uriString      = $"{serviceSetting.BaseServerUrl}{serviceSetting.BillingConfig.CreditNotesEndpoint}";
            var sapResponse    = await SendMessage(sapCreditNote, sapSystem, uriString, HttpMethod.Post);

            return(new SapTaskResult
            {
                IsSuccessful = sapResponse.IsSuccessStatusCode,
                IdUser = dequeuedTask.CreditNoteRequest?.ClientId.ToString(),
                SapResponseContent = await sapResponse.Content.ReadAsStringAsync(),
                TaskName = "Creating Credit Note Request"
            });
        }
Beispiel #2
0
        private async Task <SapTaskResult> SendIncomingPaymentToSap(SapServiceConfig serviceSetting, string sapSystem, SapSaleOrderInvoiceResponse response, string transferReference, SapLoginCookies cookies)
        {
            var billingMapper          = GetMapper(sapSystem);
            var incomingPaymentRequest = billingMapper.MapSapIncomingPayment(response.DocEntry, response.CardCode, response.DocTotal, response.DocDate, transferReference);

            var message = new HttpRequestMessage
            {
                RequestUri = new Uri($"{serviceSetting.BaseServerUrl}{serviceSetting.BillingConfig.IncomingPaymentsEndpoint}"),
                Content    = new StringContent(JsonConvert.SerializeObject(incomingPaymentRequest), Encoding.UTF8, "application/json"),
                Method     = HttpMethod.Post
            };

            message.Headers.Add("Cookie", cookies.B1Session);
            message.Headers.Add("Cookie", cookies.RouteId);

            var client      = _httpClientFactory.CreateClient();
            var sapResponse = await client.SendAsync(message);

            if (!sapResponse.IsSuccessStatusCode)
            {
                _logger.LogError($"Incoming Payment could'n create to SAP because exists an error: '{sapResponse.Content.ReadAsStringAsync()}'.");
            }

            return(new SapTaskResult
            {
                IsSuccessful = sapResponse.IsSuccessStatusCode,
                SapResponseContent = await sapResponse.Content.ReadAsStringAsync(),
                TaskName = "Creating Billing Request"
            });
        }
        private async Task <SapTaskResult> UpdateInvoice(SapTask dequeuedTask, string sapSystem, SapSaleOrderInvoiceResponse invoiceFromSap)
        {
            var billingValidator = GetValidator(sapSystem);

            if (!billingValidator.CanUpdate(invoiceFromSap, dequeuedTask.BillingRequest))
            {
                return(new SapTaskResult
                {
                    IsSuccessful = false,
                    IdUser = dequeuedTask.BillingRequest?.UserId.ToString(),
                    SapResponseContent = $"Failed at updating billing request for the invoice: {dequeuedTask.BillingRequest.InvoiceId}.",
                    TaskName = "Updating Billing Request"
                });
            }

            var serviceSetting = SapServiceSettings.GetSettings(_sapConfig, sapSystem);
            var uriString      = $"{serviceSetting.BaseServerUrl}{serviceSetting.BillingConfig.Endpoint}({invoiceFromSap.DocEntry})";
            var sapResponse    = await SendMessage(dequeuedTask.BillingRequest, sapSystem, uriString, HttpMethod.Patch);

            var taskResult = new SapTaskResult
            {
                IsSuccessful       = sapResponse.IsSuccessStatusCode,
                IdUser             = dequeuedTask.BillingRequest?.UserId.ToString(),
                SapResponseContent = await sapResponse.Content.ReadAsStringAsync(),
                TaskName           = "Updating Invoice"
            };

            return(taskResult);
        }
        public async Task CreditNoteHandler_ShouldBeCreateCreditNoteInSap_WhenQueueHasOneValidElement()
        {
            var sapSaleOrderInvoiceResponse = new SapSaleOrderInvoiceResponse
            {
                BillingSystemId = 2,
                CardCode        = "CD001",
                DocumentLines   = new List <SapDocumentLineResponse>()
            };

            var sapConfigMock = new Mock <IOptions <SapConfig> >();

            var timeZoneConfigurations = new TimeZoneConfigurations
            {
                InvoicesTimeZone = TimeZoneHelper.GetTimeZoneByOperativeSystem("Argentina Standard Time")
            };

            var dateTimeProviderMock = new Mock <IDateTimeProvider>();

            dateTimeProviderMock.Setup(x => x.UtcNow)
            .Returns(new DateTime(2019, 09, 25));

            var billingMappers = new List <IBillingMapper>
            {
                new BillingForArMapper(Mock.Of <ISapBillingItemsService>(), dateTimeProviderMock.Object, timeZoneConfigurations),
                new BillingForUsMapper(Mock.Of <ISapBillingItemsService>(), dateTimeProviderMock.Object, timeZoneConfigurations)
            };

            sapConfigMock.Setup(x => x.Value)
            .Returns(new SapConfig
            {
                SapServiceConfigsBySystem = new Dictionary <string, SapServiceConfig>
                {
                    { "US", new SapServiceConfig {
                          CompanyDB             = "CompanyDb",
                          Password              = "******",
                          UserName              = "******",
                          BaseServerUrl         = "http://123.123.123/",
                          BusinessPartnerConfig = new BusinessPartnerConfig
                          {
                              Endpoint = "BusinessPartners"
                          },
                          BillingConfig = new BillingConfig
                          {
                              Endpoint            = "Invoices",
                              CreditNotesEndpoint = "CreditNotes"
                          }
                      } }
                }
            });

            var httpClientFactoryMock  = new Mock <IHttpClientFactory>();
            var httpMessageHandlerMock = new Mock <HttpMessageHandler>();

            httpMessageHandlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(@"")
            });
            var httpClient = new HttpClient(httpMessageHandlerMock.Object);

            httpClientFactoryMock.Setup(_ => _.CreateClient(It.IsAny <string>()))
            .Returns(httpClient);

            var sapTaskHandlerMock = new Mock <ISapTaskHandler>();

            sapTaskHandlerMock.Setup(x => x.StartSession())
            .ReturnsAsync(new SapLoginCookies
            {
                B1Session = "session",
                RouteId   = "route"
            });


            sapTaskHandlerMock.Setup(x => x.TryGetInvoiceByInvoiceIdAndOrigin(It.IsAny <int>(), It.IsAny <string>()))
            .ReturnsAsync(sapSaleOrderInvoiceResponse);

            var sapServiceSettingsFactoryMock = new Mock <ISapServiceSettingsFactory>();

            sapServiceSettingsFactoryMock.Setup(x => x.CreateHandler("US")).Returns(sapTaskHandlerMock.Object);

            var handler = new CreditNoteHandler(
                sapConfigMock.Object,
                Mock.Of <ILogger <CreditNoteHandler> >(),
                sapServiceSettingsFactoryMock.Object,
                httpClientFactoryMock.Object,
                billingMappers);

            var httpResponseMessage = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent("")
            };

            httpResponseMessage.Headers.Add("Set-Cookie", "");
            httpMessageHandlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(httpResponseMessage);

            var result = await handler.Handle(new SapTask
            {
                CreditNoteRequest = new CreditNoteRequest
                {
                    BillingSystemId = 2,
                    Amount          = 100,
                    ClientId        = 1,
                    InvoiceId       = 1,
                    Type            = 1
                },
                TaskType = Enums.SapTaskEnum.CreateCreditNote
            });

            Assert.True(result.IsSuccessful);
            Assert.Equal("Creating Credit Note Request", result.TaskName);
        }