public async Task Given_ThereIsAnInvoiceWithSameIdentifierInDatabase_When_HandlerIsCalled_Then_ItShouldReturnBadRequestResponse()
        {
            //arrange
            var setupExistingInvoice = new Invoice()
            {
                Identifier = "TEST-100", Amount = 200
            };

            _applicationDbContext.Invoices.Add(setupExistingInvoice);

            await _applicationDbContext.SaveChangesAsync();

            var setupInvoiceDto = new CreateInvoiceDto()
            {
                Amount = 100, Identifier = "TEST-100"
            };
            var setupCreateInvoiceCommand = new CreateInvoiceCommand(setupInvoiceDto);

            //act
            var response = await _systemUnderTest.Handle(setupCreateInvoiceCommand, default);

            //assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
            response.Error.Should().NotBeNull();
            response.Error.ErrorCode.Should().Be(ApplicationConstants.ErrorCodes.BusinessValidationError);
            response.Error.ErrorMessage.Should().Be(string.Format(ApplicationConstants.ErrorMessages.SameIdentifierInvoice, setupExistingInvoice.Identifier));

            var countInvoices = await _applicationDbContext.Invoices.CountAsync();

            countInvoices.Should().Be(1);
        }
Пример #2
0
        public async Task <ActionResult <Tbl_Invoices> > CreateInvoice(CreateInvoiceDto request)
        {
            List <int> listOfProductIds = new List <int>();

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            if (!_customerService.IsCustomerExisting(request.customerId))
            {
                return(NotFound("Customer not found"));
            }
            //Get all list of Products Ids
            request.products.ForEach(x => listOfProductIds.Add(x.productsId));
            //Check if any Product Id is not valid

            var productResult = _productService.InvalidProducts(listOfProductIds);

            if (productResult.Any())
            {
                return(NotFound("Some Products Ids were Invalid: " + String.Join(",", productResult)));
            }
            var result = await _invoiceService.CreateInvoiceAsync(request);

            return(CreatedAtAction("GetTotalAmountByInvoiceNumber", new { id = result.id }, result));
        }
Пример #3
0
        public async Task CreateInvoice(CreateInvoiceDto input)
        {
            var payment = await _subscriptionPaymentRepository.GetAsync(input.SubscriptionPaymentId);

            if (!string.IsNullOrEmpty(payment.InvoiceNo))
            {
                throw new Exception("Invoice is already generated for this payment.");
            }

            var invoiceNo = await _invoiceNumberGenerator.GetNewInvoiceNumber();

            var tenantLegalName = await SettingManager.GetSettingValueAsync(AppSettings.TenantManagement.BillingLegalName);

            var tenantAddress = await SettingManager.GetSettingValueAsync(AppSettings.TenantManagement.BillingAddress);

            var tenantTaxNo = await SettingManager.GetSettingValueAsync(AppSettings.TenantManagement.BillingTaxVatNo);

            if (string.IsNullOrEmpty(tenantLegalName) || string.IsNullOrEmpty(tenantAddress) || string.IsNullOrEmpty(tenantTaxNo))
            {
                throw new UserFriendlyException(L("InvoiceInfoIsMissingOrNotCompleted"));
            }

            await _invoiceRepository.InsertAsync(new Invoice
            {
                InvoiceNo       = invoiceNo,
                InvoiceDate     = Clock.Now,
                TenantLegalName = tenantLegalName,
                TenantAddress   = tenantAddress,
                TenantTaxNo     = tenantTaxNo
            });

            payment.InvoiceNo = invoiceNo;
        }
Пример #4
0
 public async Task Create(CreateInvoiceDto input)
 {
     await _invoiceManager.Create(
         input.ProductName,
         input.SubTotal,
         input.AuctionId,
         input.SerialNumber
         );
 }
        public async Task <IActionResult> SendAppointmentsInvoice([FromBody] CreateInvoiceDto invoiceDto)
        {
            var invoiceModel = await _financialReportService.CreateInvoiceReportModel(invoiceDto.ClientId, invoiceDto.AppointmentId);

            byte[] invoiceReport = await _financialReportService.GenerateInvoice(invoiceModel);

            await _emailNotificationService.SendClientAppointmentsInvoice(invoiceDto.ClientId, invoiceReport);

            return(NoContent());
        }
Пример #6
0
        public async Task <string> CreateInvoiceAsync(CreateInvoiceDto model)
        {
            var invoice = model.MapToInvoice();

            var faker = new Faker();

            invoice.CreationDate    = DateTime.Now;
            invoice.ExternalOrderId = faker.Commerce.Ean13();
            invoice.PaymentFormUrl  = faker.Internet.Url();

            await _context.AddAsync(invoice);

            await _context.SaveChangesAsync();

            return(invoice.PaymentFormUrl);
        }
Пример #7
0
        public async Task <ActionResult <string> > CreateInvoice(CreateInvoiceDto model)
        {
            if (model.CartItems.Count == 0)
            {
                return(BadRequest());
            }

            try
            {
                var paymentFormUrl = await _paymentService.CreateInvoiceAsync(model);

                return(Created(string.Empty, paymentFormUrl));
            }
            catch (Exception)
            {
                return(UnprocessableEntity());
            }
        }
Пример #8
0
        public async Task <ActionResult> CreateInvoice(CreateInvoiceDto dto)
        {
            await _invoiceAppService.CreateAsync(dto);

            foreach (var items in dto.InvoiceDetails)
            {
                var check = await _stockService.CheckIfExist(items.ProductId);

                if (check != null)
                {
                    check.TotalPieces -= items.TotalPieces;
                    check.Amount      -= items.Amount;
                    await _stockService.UpdateAsync(check);
                }
            }

            return(Ok(dto));
        }
Пример #9
0
 public static Invoice MapToInvoice(this CreateInvoiceDto model)
 {
     return(new Invoice
     {
         OrderId = model.OrderId,
         CartItems = model.CartItems != null
             ? model.CartItems
                     .Select(i => new CartItem
         {
             PositionId = i.PositionId,
             Name = i.Name,
             ItemCode = i.ItemCode,
             ItemAmount = i.ItemAmount,
             Quantity = i.Quantity
         })
                     .ToList()
             : new List <CartItem>()
     });
 }
        public void Given_TheCallIsCancelledByUser_When_HandlerIsCalled_Then_TheHandlerShouldThrowOperationCancelledException()
        {
            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                var cancellationToken = cancellationTokenSource.Token;
                cancellationTokenSource.Cancel();

                var setupInvoiceDto = new CreateInvoiceDto()
                {
                    Amount = 100, Identifier = "TEST-100"
                };

                var setupCreateInvoiceCommand = new CreateInvoiceCommand(setupInvoiceDto);

                Func <Task <CreateInvoiceCommandResponse> > func = async() => await _systemUnderTest.Handle(setupCreateInvoiceCommand, cancellationToken);

                func.Should().ThrowAsync <OperationCanceledException>();
            }
        }
Пример #11
0
        public async Task <IActionResult> GenerateInvoiceForACustomer(int userId, [FromBody] CreateInvoiceDto invoiceDto)
        {
            decimal invoiceSubtotal = 0;
            var     user            = await _repository.User.GetCustomerById(userId, false);

            if (user == null)
            {
                return(NotFound());
            }

            invoiceSubtotal = await ApplyDiscount(invoiceDto, invoiceSubtotal, user);

            var invoiceEntity = _mapper.Map <Invoice>(invoiceDto);

            invoiceEntity.Total = invoiceSubtotal;
            _repository.Invoice.GenerateInvoiceForCustomer(userId, invoiceEntity);
            await _repository.SaveAsync();

            return(Ok());
        }
        public async Task Given_TheSaveInvoiceFailsInDatabase_When_HandlerIsCalled_Then_ItShouldReturnInternalServerError()
        {
            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                //arrange
                var cancellationToken = cancellationTokenSource.Token;

                var setupException = new Exception("test save exception");

                var setupInvoiceDto = new CreateInvoiceDto()
                {
                    Amount = 100, Identifier = "TEST-100"
                };

                var setupCreateInvoiceCommand = new CreateInvoiceCommand(setupInvoiceDto);

                var mockApplicationUnitOfWork = _mockRepository.Create <IApplicationUnitOfWork>();
                var mockInvoiceRepository     = _mockRepository.Create <IApplicationRepository <Invoice> >();

                mockInvoiceRepository.Setup(x => x.SingleOrDefaultAsync(It.IsAny <Expression <Func <Invoice, bool> > >(), It.IsAny <CancellationToken>()))
                .ReturnsAsync(null as Invoice);
                mockInvoiceRepository.Setup(x => x.AddAsync(It.IsAny <Invoice>()))
                .ReturnsAsync(null as Invoice);

                mockApplicationUnitOfWork.Setup(x => x.CommitAsync(cancellationToken)).ThrowsAsync(setupException);
                mockApplicationUnitOfWork.Setup(x => x.Invoices).Returns(mockInvoiceRepository.Object);

                _systemUnderTest = new CreateInvoiceCommandHandler(mockApplicationUnitOfWork.Object, _logger.Object, _mapper);

                //act
                var response = await _systemUnderTest.Handle(setupCreateInvoiceCommand, cancellationToken);

                //assert
                response.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
                response.Error.Should().NotBeNull();
                response.Error.ErrorCode.Should().Be(ApplicationConstants.ErrorCodes.CreateInvoiceError);
                response.Error.ErrorMessage.Should().Be(setupException.Message);
            }
        }
Пример #13
0
        private async Task <decimal> ApplyDiscount(CreateInvoiceDto invoiceDto, decimal invoiceSubtotal, Users user)
        {
            var discounts = await _repository.Discount.GetAllDiscounts(false);

            foreach (var discount in discounts)
            {
                if (discount.Equals(user.UserType) && discount.IsRatePercentage)
                {
                    var discountValue = invoiceDto.OrderTotal * (discount.Rate / 100);
                    invoiceSubtotal = invoiceDto.OrderTotal - discountValue;
                }

                foreach (var detail in invoiceDto.InvoiceDetails)
                {
                    if (detail.DerivedProductCost >= 100 && !discount.IsRatePercentage)
                    {
                        invoiceSubtotal -= discount.Rate;
                    }
                }
            }

            return(invoiceSubtotal);
        }
        public async Task Given_ThereIsAValidInvoice_When_HandlerIsCalled_Then_TheInvoiceIsSavedAndReturned()
        {
            //arrange
            var setupInvoiceDto = new CreateInvoiceDto()
            {
                Amount = 100, Identifier = "TEST-100"
            };

            var setupCreateInvoiceCommand = new CreateInvoiceCommand(setupInvoiceDto);

            //act
            var response = await _systemUnderTest.Handle(setupCreateInvoiceCommand, default);

            //assert
            response.StatusCode.Should().Be(HttpStatusCode.Created);
            response.Error.Should().BeNull();
            response.HasError.Should().BeFalse();

            response.Content.Should().NotBeNull();
            response.Content.InvoiceId.Should().Be(1);
            response.Content.Amount.Should().Be(setupInvoiceDto.Amount);
            response.Content.Identifier.Should().Be(setupInvoiceDto.Identifier);
            response.Content.CreatedBy.Should().Be(_testUserId);
        }
Пример #15
0
        public async Task <ActionResult <InvoiceDto> > CreateInvoice([FromBody] CreateInvoiceDto createInvoiceModel, CancellationToken cancellationToken)
        {
            var response = await _mediator.Send(new CreateInvoiceCommand(createInvoiceModel), cancellationToken);

            return(ProcessResult(response));
        }
        public IActionResult SaveInvoice([FromBody] CreateInvoiceDto body)
        {
            Response response = new Response();

            response.data = new List <Invoice>();

            var transaction = this._context.Database.BeginTransaction();

            try {
                var     clientExists   = this._context.Client.SingleOrDefault(t => t.card_id == body.clientId);
                decimal subtotalAmount = 0;
                decimal totalTaxes     = 0;

                if (clientExists == null)
                {
                    clientExists = new Client {
                        card_id = body.clientId, name = body.clientName, address = body.clientAddress, phone_number = body.clientPhone, created_at = DateTime.Now
                    };
                    this._context.Client.Add(clientExists);
                }

                Invoice invoice = new Invoice {
                    client = clientExists, created_at = DateTime.Now, delivery = Params.DELIVERY, invoiceProducts = new List <InvoiceHasProduct>()
                };

                this._context.Invoice.Add(invoice);
                this._context.SaveChanges();

                for (int i = 0; i < body.products.Count; i++)
                {
                    var product = this._context.Product.SingleOrDefault(t => t.id == body.products[i].id);

                    if (product == null)
                    {
                        throw new Exception("Product: " + body.products[i].id + " not found ...");
                    }

                    subtotalAmount += (product.unit_price * body.products[i].quantity);
                    totalTaxes     += (product.taxes * body.products[i].quantity);

                    InvoiceHasProduct invoiceProduct = new InvoiceHasProduct {
                        invoice_id = invoice.id, product_id = product.id, quantity = body.products[i].quantity, product = product
                    };
                    invoice.invoiceProducts.Add(invoiceProduct);
                }

                invoice.subtotal_amount = subtotalAmount;
                invoice.included_taxes  = totalTaxes;
                invoice.total_amount    = invoice.subtotal_amount + invoice.delivery;

                this._context.Update(invoice);
                this._context.SaveChanges();
                transaction.Commit();

                response.code    = 1;
                response.message = "Ok";
                response.data.Add(invoice);
                return(Ok(invoice));
            } catch (Exception e) {
                transaction.Rollback();

                response.code    = 0;
                response.message = e.Message;
                return(BadRequest(response));
            }
        }
Пример #17
0
        public async Task <Tbl_Invoices> CreateInvoiceAsync(CreateInvoiceDto requests)
        {
            var user = await _customerService.GetCustomerByIdAsync(requests.customerId);

            //Add products
            var invoice = await AddProductsToInvoice(requests.products);

            invoice.customer   = user;
            invoice.customerId = user.id;

            //Calculate Affiliate Discount 10 percent
            if (user.isAffiliate)
            {
                var percentage = Convert.ToDecimal(10F / 100);
                var total      = percentage * invoice.totalAmount;
                invoice.totalDiscountAmount = total;
            }

            //Calculate Employee Discount 5 percent
            if (user.isCustomerLoyal())
            {
                var percentage = Convert.ToDecimal(5F / 100);
                var total      = percentage * invoice.totalAmount;
                invoice.totalDiscountAmount = total;
            }

            //Customer can only get one percentage based discount
            //Calculate Employee Discount 30 percent
            if (user.isEmployee)
            {
                var percentage = Convert.ToDecimal(30F / 100);
                var total      = percentage * invoice.totalAmount;
                invoice.totalDiscountAmount = total;
            }

            //Calculate 5% discount on every $100
            var discountedAmount = 100;
            var x             = invoice.totalAmount % discountedAmount;
            var y             = invoice.totalAmount - x;
            var z             = y / discountedAmount;
            var totalDiscount = z * 5;

            invoice.billDiscountAmount     = totalDiscount;
            invoice.billDiscountPercentage = 5;

            invoice.totalDiscountAmount = invoice.totalDiscountAmount + totalDiscount;
            invoice.updateTotalWithDiscount();
            invoice.issueDate = DateTime.Now;

            //Save to Db
            try{
                await _context.Tbl_Invoices.AddAsync(invoice);

                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                throw;
            }
            return(invoice);
        }
Пример #18
0
 public async Task <int> Create([Required] CreateInvoiceDto dto, CancellationToken cancellationToken)
 {
     return(await _commandDispatcher.HandleAsync(new CreateInvoiceCommand(dto), cancellationToken));
 }