예제 #1
0
        public Invoice CreateInvoice(InvoiceForCreationDto inputInvoice)
        {
            // determine current New Zealand time
            TimeZoneInfo tz       = TimeZoneInfo.FindSystemTimeZoneById("New Zealand Standard Time");
            DateTime     localNow = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz);

            // copy information provided by the client
            Invoice invoice = mapper.Map <Invoice>(inputInvoice);

            invoice.InvoiceNumber   = GenerateOrganisationInvoiceNumber(inputInvoice.LoginId);
            invoice.CharitiesNumber = options.CharitiesNumber;
            invoice.GstNumber       = options.GSTNumber;
            invoice.GstRate         = options.GSTRate;
            invoice.DateCreated     = localNow;
            invoice.Status          = InvoiceStatus.Draft;
            invoice.Creator         = context.User.FirstOrDefault(u => u.Email == inputInvoice.LoginId);

            Validate(invoice);

            context.Add <Invoice>(invoice);
            int count = context.SaveChanges();

            if (count > 0)
            {
                return(invoice);
            }
            else
            {
                return(null);
            }
        }
        public void CreateInvoiceShould_RequireProperties()
        {
            // arrange
            var context = new CBAContext(dboptions);
            var service = new InvoiceService(context, options, mapper, pdf, logger);
            var invoice = new InvoiceForCreationDto()
            {
                ClientName          = "",
                ClientContactPerson = "Glen Clarke",
                ClientContact       = "530/546A Memorial Ave\\r\\nChristchurch Airport\\r\\nChristchurch 8053",
                InvoiceLine         = null
            };

            // act
            bool success = false;

            try
            {
                var result = service.CreateInvoice(invoice);
            }
            catch (ValidationException)
            {
                success = true;
            }
            // assert
            Assert.IsTrue(success);
        }
        public async Task <IActionResult> CreateInvoice([FromBody] InvoiceForCreationDto invoice)
        {
            try
            {
                if (invoice == null)
                {
                    _logger.LogError("Invoice received is a Null Object.");
                    return(BadRequest("Invoice object is null. Please send full request."));
                }
                else if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid Invoice object sent from client.");
                    return(BadRequest("Invoice object is not Valid"));
                }

                Boolean rentExist = await _repositoryWrapper.Rent.CheckIfRentExistByRentId(invoice.RentId);

                if (!rentExist)
                {
                    _logger.LogError($"Invoice cannot be created, because Rent with id:{invoice.RentId} does not exist in DB.");
                    return(BadRequest($"Not created. Rent wiht id: {invoice.RentId} does not exist."));
                }

                Boolean stateHasInvoice = await _repositoryWrapper.Invoice.CheckIfInvoiceExistByStateId(invoice.StateId);

                if (stateHasInvoice)
                {
                    _logger.LogError($"Invoice cannot be created, because State with id:{invoice.StateId} already exist.");
                    return(BadRequest($"Not created. Invoice for this State_id: {invoice.StateId} already exist"));
                }

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

                _repositoryWrapper.Invoice.CreateInvoice(invoiceEntity);
                await _repositoryWrapper.Save();

                var createdInvoice = _mapper.Map <InvoiceDto>(invoiceEntity);

                /* Get generatedInvoice and update previously created invoice in this process. */
                var pdfFileToInclude = await GetGeneratedPDF(createdInvoice.Id);

                createdInvoice.InvoiceDocument = pdfFileToInclude.getInvoiceBytes();
                createdInvoice.FileName        = pdfFileToInclude.getInvoiceFileName();
                /* map created invoice to InvoiceForUpdateDto */
                invoiceEntity.InvoiceDocument = pdfFileToInclude.getInvoiceBytes();
                invoiceEntity.FileName        = pdfFileToInclude.getInvoiceFileName();
                _repositoryWrapper.Invoice.UpdateInvoice(invoiceEntity);
                await _repositoryWrapper.Save();

                /* Modofication end 03.06. */

                return(CreatedAtRoute("InvoiceById", new { id = createdInvoice.Id }, createdInvoice));
            }
            catch (Exception e)
            {
                _logger.LogError($"Something went wrong inside CreateInvoice() action: {e.Message}");
                return(StatusCode(500, e.Message));
            }
        }
예제 #4
0
        public void AddInvoice(InvoiceForCreationDto invoice, List <SelectingProductForSellDto> products)
        {
            // 1. add custom?
            var phoneNumber = invoice.PhoneNumber;

            // check if it's existing?
            var customer   = _customerRepository.GetCustomByPhoneNumber(phoneNumber);
            var customerId = -1;

            if (customer == null)
            {
                customer = new Customer {
                    Name = invoice.CustomerName, PhoneNumber = phoneNumber, CreationTime = DateTime.Now, AccumulatedPoint = invoice.Price / 100000
                };
                if (customer.AccumulatedPoint >= _customerLevelRepository.GetCustomerLevelByName("Hạng Vàng").PointLevel)
                {
                    customer.CustomerLevelId = 3;
                }
                else if (customer.AccumulatedPoint >= _customerLevelRepository.GetCustomerLevelByName("Hạng Bạc").PointLevel)
                {
                    customer.CustomerLevelId = 2;
                }
                else
                {
                    customer.CustomerLevelId = 1;
                }
                var storedCustomer = _customerRepository.Create(customer);
                customerId = storedCustomer.Id;
            }
            else
            {
                customerId = customer.Id;
            }

            // 2. add invoice
            var storedInvoice = _invoiceRepository.Create(new Invoice
            {
                CustomerId   = customerId,
                UserId       = Session.CurrentUser.Id,
                CreationTime = DateTime.Now,
                Total        = invoice.Total,
                Discount     = invoice.Discount,
                Price        = invoice.Price
            });;

            // 3. add invoice's products and decrease no. each product
            foreach (var product in products)
            {
                var invoiceProduct = new InvoiceProduct
                {
                    ProductId = product.Id,
                    Number    = product.SelectedNumber,
                    InvoiceId = storedInvoice.Id
                };

                _invoiceProductRepository.Create(invoiceProduct);
                _productRepository.UpdateNumberById(product.Id, product.SelectedNumber);
            }
        }
예제 #5
0
        public IActionResult CreateInvoice([FromBody] InvoiceForCreationDto invoice)
        {
            try
            {
                Invoice created = service.CreateInvoice(invoice);
                if (created != null)
                {
                    var createdDto = mapper.Map <InvoiceDto>(created);
                    return(CreatedAtAction(
                               "GetInvoice",
                               new { created.InvoiceNumber },
                               createdDto));
                }
            }
            catch (ValidationException ex)
            {
                return(BadRequest(ex.Message));
            }

            return(StatusCode(500, "Failed to create new invoice."));
        }
        public void CreateInvoiceShould_CreateInvoice()
        {
            // arrange
            var context = new CBAContext(dboptions);
            var service = new InvoiceService(context, options, mapper, pdf, logger);

            var invoice = new InvoiceForCreationDto()
            {
                LoginId             = "LoginFoo",
                ClientName          = "Electrocal Commission",
                ClientContactPerson = "Glen Clarke",
                ClientContact       = "530/546A Memorial Ave\\r\\nChristchurch Airport\\r\\nChristchurch 8053",
                Email       = "*****@*****.**",
                InvoiceLine = new List <InvoiceLineDto>()
                {
                    new InvoiceLineDto()
                    {
                        Description = "Fundraising Dinner",
                        Amount      = 25
                    },
                    new InvoiceLineDto()
                    {
                        Description = "Cake",
                        Amount      = 35
                    }
                }
            };

            // act
            var result = service.CreateInvoice(invoice);

            // assert
            Assert.IsTrue(result != null);
            using (var cleancontext = new CBAContext(dboptions))
            {
                Assert.IsTrue(context.Invoice.Any());
                Assert.IsTrue(context.Invoice.FirstOrDefault().InvoiceLine.Count() == 2);
            }
        }
예제 #7
0
        public async Task <IActionResult> UpdateDepartment(string startDate, string endDate, int id, InvoiceForCreationDto invoiceForCreationDto)
        {
            int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            string sql = $"EXEC dbo.spUpdateInvoice @Date='{invoiceForCreationDto.Date}', @Customer='{invoiceForCreationDto.Customer}', " +
                         $"@InvoiceNumber={invoiceForCreationDto.InvoiceNumber}, @StartDate='{startDate}', @EndDate='{endDate}', " +
                         $"@DateRange='{invoiceForCreationDto.DateRange}', @UserId={userId}";

            Invoice invoice = await _sqlAccess.ExecuteProcedure <Invoice>(sql);

            if (await _repo.SaveAll())
            {
                var invoiceToReturn = _mapper.Map <InvoiceForReturnDto>(invoice);
                return(CreatedAtRoute("GetInvoice", new { id = invoice.Id }, invoiceToReturn));
            }

            throw new Exception("Updating invoice failed on save");
        }
예제 #8
0
        public async Task <IActionResult> AddInvoice(string startDate, string endDate, InvoiceForCreationDto invoiceForCreation)
        {
            int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            string sql = $"EXEC dbo.spUpdateClockItemsInvoiced @Invoiced=1, @Date='{invoiceForCreation.Date}', @Customer='{invoiceForCreation.Customer}', " +
                         $"@InvoiceNumber={invoiceForCreation.InvoiceNumber}, @StartDate='{startDate}', @EndDate='{endDate}', " +
                         $"@DateRange='{invoiceForCreation.DateRange}', @UserId={userId}";

            Console.WriteLine(sql);

            Invoice invoice = await _sqlAccess.ExecuteProcedure <Invoice>(sql);

            InvoiceForReturnDto invoiceToReturn = _mapper.Map <InvoiceForReturnDto>(invoice);

            return(CreatedAtRoute("GetInvoice", new { id = invoice.Id }, invoiceToReturn));

            throw new Exception("Creation of invoice failed on save");
        }