public async Task <IActionResult> Put(int id, [FromBody] InvoiceLineViewModel input, CancellationToken ct = default(CancellationToken))
        {
            try
            {
                if (input == null)
                {
                    return(BadRequest());
                }
                if (await _chinookSupervisor.GetInvoiceLineByIdAsync(id, ct) == null)
                {
                    return(NotFound());
                }
                var errors = JsonConvert.SerializeObject(ModelState.Values
                                                         .SelectMany(state => state.Errors)
                                                         .Select(error => error.ErrorMessage));
                Debug.WriteLine(errors);

                if (await _chinookSupervisor.UpdateInvoiceLineAsync(input, ct))
                {
                    return(Ok(input));
                }

                return(StatusCode(500));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex));
            }
        }
Ejemplo n.º 2
0
        public IActionResult EditLineJson(InvoiceLineViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var result = InvoiceManager.EditLine(model, CurrentUser, false, true);

                    return(Json(new
                    {
                        success = true,
                        InvoiceLine = result
                    }));
                }
            }
            catch (Exception e)
            {
                var innerMessage = e.InnerException == null ? "" : $": {e.InnerException.Message}";

                ModelState.AddModelError("", e.Message + innerMessage);
            }

            return(Json(new
            {
                success = false,
                errors = ModelState.Keys.SelectMany(k => ModelState[k].Errors)
                         .Select(m => m.ErrorMessage).ToArray()
            }));
        }
        public static InvoiceLineViewModel Convert(InvoiceLine invoiceLine)
        {
            var invoiceLineViewModel = new InvoiceLineViewModel();

            invoiceLineViewModel.InvoiceLineId = invoiceLine.InvoiceLineId;
            invoiceLineViewModel.InvoiceId     = invoiceLine.InvoiceId;
            invoiceLineViewModel.TrackId       = invoiceLine.TrackId;
            invoiceLineViewModel.UnitPrice     = invoiceLine.UnitPrice;
            invoiceLineViewModel.Quantity      = invoiceLine.Quantity;

            return(invoiceLineViewModel);
        }
Ejemplo n.º 4
0
        public static InvoiceLineViewModel Convert(InvoiceLine invoiceLine)
        {
            var invoiceLineViewModel = new InvoiceLineViewModel
            {
                InvoiceLineId = invoiceLine.InvoiceLineId,
                InvoiceId     = invoiceLine.InvoiceId,
                TrackId       = invoiceLine.TrackId,
                UnitPrice     = invoiceLine.UnitPrice,
                Quantity      = invoiceLine.Quantity
            };

            return(invoiceLineViewModel);
        }
 public static List <InvoiceLineViewModel> ConvertList(IEnumerable <InvoiceLine> invoiceLines)
 {
     return(invoiceLines.Select(i =>
     {
         var model = new InvoiceLineViewModel();
         model.InvoiceLineId = i.InvoiceLineId;
         model.InvoiceId = i.InvoiceId;
         model.TrackId = i.TrackId;
         model.UnitPrice = i.UnitPrice;
         model.Quantity = i.Quantity;
         return model;
     })
            .ToList());
 }
 public async Task <IActionResult> Post([FromBody] InvoiceLineViewModel input, CancellationToken ct = default(CancellationToken))
 {
     try
     {
         if (input == null)
         {
             return(BadRequest());
         }
         return(Ok(await _chinookSupervisor.AddInvoiceLineAsync(input, ct)));
     }
     catch (Exception ex)
     {
         return(StatusCode(500, ex));
     }
 }
Ejemplo n.º 7
0
        public async Task <InvoiceLineViewModel> AddInvoiceLineAsync(InvoiceLineViewModel newInvoiceLineViewModel, CancellationToken ct = default(CancellationToken))
        {
            var invoiceLine = new InvoiceLine
            {
                InvoiceId = newInvoiceLineViewModel.InvoiceId,
                TrackId   = newInvoiceLineViewModel.TrackId,
                UnitPrice = newInvoiceLineViewModel.UnitPrice,
                Quantity  = newInvoiceLineViewModel.Quantity
            };

            invoiceLine = await _invoiceLineRepository.AddAsync(invoiceLine, ct);

            newInvoiceLineViewModel.InvoiceLineId = invoiceLine.InvoiceLineId;
            return(newInvoiceLineViewModel);
        }
Ejemplo n.º 8
0
        public async Task <bool> UpdateInvoiceLineAsync(InvoiceLineViewModel invoiceLineViewModel, CancellationToken ct = default(CancellationToken))
        {
            var invoiceLine = await _invoiceLineRepository.GetByIdAsync(invoiceLineViewModel.InvoiceId, ct);

            if (invoiceLine == null)
            {
                return(false);
            }
            invoiceLine.InvoiceLineId = invoiceLineViewModel.InvoiceLineId;
            invoiceLine.InvoiceId     = invoiceLineViewModel.InvoiceId;
            invoiceLine.TrackId       = invoiceLineViewModel.TrackId;
            invoiceLine.UnitPrice     = invoiceLineViewModel.UnitPrice;
            invoiceLine.Quantity      = invoiceLineViewModel.Quantity;

            return(await _invoiceLineRepository.UpdateAsync(invoiceLine, ct));
        }
Ejemplo n.º 9
0
        public void AddUpdateInvoice_Test()
        {
            #region Data
            int              mrmUserId    = 1;
            string           networkLogin = "******";
            InvoiceViewModel viewModel    = new InvoiceViewModel()
            {
                Id            = 0,
                Vendor        = 142,
                PaymentTerm   = 9,
                Status        = 2,
                InvoiceNumber = "123",
                InvoiceDate   = DateTime.Now,
                PostingDate   = DateTime.Now,
                Comments      = "Invoice Creation Comments",
                WebUser       = 123,//mrmuserId,
                timestamp     = null
            };
            List <InvoiceLineViewModel> lstInvoiceLines = new List <InvoiceLineViewModel>();
            InvoiceLineViewModel        invoiceLine1    = new InvoiceLineViewModel()
            {
                ContractNumber      = "1234",
                PurchaseOrderNumber = "Abcd1234",
                Description         = "Test InvoiceLine1 to insert",
                Comment             = "Test Comment to insert",
                Amount = 250,
                DeliverableBudgetId = 129289,
                GLAccountId         = 50,
                Id = 1,
                ProductionMethodType = 2,
                WBSElementId         = 3250,
                WBSNumber            = "1146",
                Coding = "",
                ChannelCostCenterId   = 21,
                ChannelProfitCenterId = null,
            };
            InvoiceLineViewModel invoiceLine2 = new InvoiceLineViewModel()
            {
                ContractNumber      = "2345",
                PurchaseOrderNumber = "Abcd2345",
                Description         = "Test InvoiceLine2 to insert",
                Comment             = "Test Comment to insert",
                Amount = 124,
                DeliverableBudgetId = 13458,
                GLAccountId         = 50,
                Id = 1,
                ProductionMethodType = 1,
                WBSElementId         = 3250,
                WBSNumber            = "1146",
                Coding = "",
                ChannelCostCenterId   = null,
                ChannelProfitCenterId = 21
            };
            Vendor vendor = new Vendor()
            {
                Name = "TestVendor1",
                Id   = 1,
            };
            InvoiceStatus status = new InvoiceStatus()
            {
                Id   = 1,
                Name = "In Progress"
            };

            lstInvoiceLines.Add(invoiceLine1);
            lstInvoiceLines.Add(invoiceLine2);
            viewModel.InvoiceLines = lstInvoiceLines;
            InvoiceHeader theInvoice = FinanceMapper.ToInvoice(viewModel);
            theInvoice.Vendor        = vendor;
            theInvoice.InvoiceStatus = status;
            InvoiceHeader theInvoice1 = FinanceMapper.ToInvoice(viewModel);
            theInvoice1.Id = 999;
            #endregion

            #region  Mock
            //invoiceHeaderRepository  Mock
            mockInvoiceHeaderRepository.Setup(x => x.Add(It.IsAny <InvoiceHeader>())).Returns(theInvoice);
            //iunit Mock
            mockIUnitOfWork.Setup(x => x.Commit());
            //IInvoiceLine Repository Mock
            mockIInvoiceLineRepository.Setup(x => x.Add(It.IsAny <InvoiceLine>())).Returns(() => null);
            //FinanceService Service Mock
            mockFinanceService.Setup(x => x.AddInvoice(It.IsAny <InvoiceHeader>())).Returns(theInvoice);
            mockFinanceService.Setup(x => x.GetInvoiceById(It.IsAny <int>())).Returns(theInvoice);
            this.mockInvoiceHeaderRepository.Setup(x => x.GetById(It.IsAny <long>())).Returns(theInvoice);
            this.mockInvoiceHeaderRepository.Setup(x => x.GetById(It.IsAny <long>())).Returns(theInvoice1);
            mockInvoiceHeaderRepository.Setup(x => x.GetInvoiceById(It.IsAny <int>())).Returns(theInvoice);
            mockIInvoiceLineRepository.Setup(x => x.GetMany(It.IsAny <Expression <Func <InvoiceLine, bool> > >()))
            .Returns(new List <InvoiceLine>());
            mockIInvoiceLineRepository.Setup(x => x.GetById(It.IsAny <long>()))
            .Returns(new InvoiceLine());
            mockInvoiceHeaderRepository.Setup(x => x.Update(It.IsAny <InvoiceHeader>()));
            mockIInvoiceLineRepository.Setup(x => x.Update(It.IsAny <InvoiceLine>()));
            //mock to finance Service
            FinanceServiceMock financeService = new FinanceServiceMock(
                invoiceHeaderRepository: mockInvoiceHeaderRepository.Object, unitOfWork: mockIUnitOfWork.Object, invoiceLineRepository: mockIInvoiceLineRepository.Object);

            //Finance Controller Mock
            var FinanceController = new FinanceControllerMock(financeServicee: financeService);
            #endregion

            #region Assertions
            mockInvoiceHeaderRepository.Verify();
            mockIUnitOfWork.Verify();
            mockIInvoiceLineRepository.Verify();
            mockFinanceService.Verify();

            //Mapping the viewmodel to actual Table
            var serviceResult = financeService.AddInvoice(theInvoice);
            Assert.IsNotNull(serviceResult);
            Assert.IsNotNull(serviceResult.InvoiceLine);
            Assert.AreEqual(serviceResult.Id, 0);//The actual Id is auto generated after insertion done in DB.
            //As we are passing 0 as invoice headerId for the purpose of insertion here we recieve the same.

            var controllerResult = FinanceController.AddUpdateInvoice(viewModel, mrmUserId, networkLogin);
            Assert.IsNotNull(controllerResult);
            Assert.AreEqual(controllerResult.Success, true);
            Assert.IsNotNull(controllerResult.Data);

            //Service N Controller Assertions for Updating Invoice
            viewModel.Id = 999;

            //Mapping the viewmodel to actual Table
            var serviceResultForUpdate = financeService.UpdateInvoice(theInvoice1);
            Assert.IsNotNull(serviceResultForUpdate);
            Assert.IsNotNull(serviceResultForUpdate.InvoiceLine);
            Assert.AreEqual(serviceResultForUpdate.Id, 999);//Here we will recieve the same invoice header id we passed for update

            var controllerUpdateResult = FinanceController.AddUpdateInvoice(viewModel, mrmUserId, networkLogin);
            Assert.IsNotNull(controllerUpdateResult);
            Assert.AreEqual(controllerUpdateResult.Success, true);
            Assert.IsNotNull(controllerUpdateResult.Data);
            #endregion
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Modify Invoice line based on given InvoiceLineViewModel or throws exceptions if invoice not found.
        /// </summary>
        /// <param name="model">InvoiceLineViewModel</param>
        /// <param name="modifiedBy">ApplicationUser that is modifying invoice line</param>
        /// <param name="recalculateInvoiceValues">Indicates if invoice line values should be recalculated based on price, tax rate, currency rate</param>
        /// <param name="recalculateBudgetValues">indicates if recalculation of budget invoiced amount should to be done</param>
        /// <returns>InvoiceLineReturnResult with line id, invoice id, line number and status</returns>
        public InvoiceLineReturnResult EditLine(InvoiceLineViewModel model, ApplicationUser modifiedBy, bool recalculateInvoiceValues, bool recalculateBudgetValues)
        {
            if (model == null || modifiedBy == null)
            {
                throw new ArgumentNullException(nameof(model), "Nieprawidłowe parametry");
            }

            var invoiceLine = GetInvoiceLineById(model.Id, model.InvoiceId, IncludeLevel.Level1);

            if (invoiceLine.Status == Status.Cancelled)
            {
                throw new InvalidOperationException("Linia fatury jest anulowana. Nie można edytować anulowanej linii faktury");
            }

            decimal netto     = model.Netto;
            decimal tax       = model.Tax;
            decimal gross     = model.Gross;
            decimal baseNetto = model.BaseNetto;
            decimal baseTax   = model.BaseTax;
            decimal baseGross = model.BaseGross;

            if (recalculateInvoiceValues)
            {
                netto = model.Quantity * model.Price;
                tax   = model.Netto * (model.TaxRate / 100);
                gross = netto + tax;

                if (model.Currency.ToUpper() == "PLN")
                {
                    baseNetto = netto;
                    baseTax   = tax;
                    baseGross = gross;
                }
                else
                {
                    baseNetto = model.CurrencyRate == 0 ? 0 : netto * model.CurrencyRate;
                    baseTax   = baseNetto * (model.TaxRate / 100);
                    baseGross = baseNetto + baseTax;
                }
            }

            var now = DateHelper.GetCurrentDatetime();


            if (invoiceLine.BudgetId != model.BudgetId)
            {
                BudgetManager.UpdateBudgetInvoicedAmount(invoiceLine.BudgetId, -baseNetto, recalculateBudgetValues);
                BudgetManager.UpdateBudgetInvoicedAmount(model.BudgetId, baseNetto, recalculateBudgetValues);
            }

            invoiceLine.LastModifiedById = modifiedBy.Id;
            invoiceLine.LastModifiedDate = now;
            invoiceLine.ItemName         = model.ItemName;
            invoiceLine.Description      = model.Description;
            invoiceLine.Quantity         = model.Quantity;
            invoiceLine.Price            = model.Price;
            invoiceLine.Currency         = model.Currency;
            invoiceLine.CurrencyRate     = model.CurrencyRate;
            invoiceLine.TaxRate          = model.TaxRate;
            invoiceLine.Netto            = netto;
            invoiceLine.Tax       = tax;
            invoiceLine.Gross     = gross;
            invoiceLine.BaseNetto = baseNetto;
            invoiceLine.BaseTax   = baseTax;
            invoiceLine.BaseGross = baseGross;
            invoiceLine.BudgetId  = model.BudgetId;

            Context.InvoiceLines.Update(invoiceLine);
            var result = Context.SaveChanges();

            if (result == 0)
            {
                throw new Exception("Nie zapisano żadnych danych.");
            }

            //return new []{ newInvoiceLine.Id, newInvoiceLine.InvoiceId, newInvoiceLine.LineNumber.ToString(), newInvoiceLine.Status.ToString() };
            return(new InvoiceLineReturnResult()
            {
                Id = invoiceLine.Id,
                InvoiceId = invoiceLine.InvoiceId,
                InvoiceNumber = invoiceLine.Invoice.InvoiceNumber,
                LineNumber = invoiceLine.LineNumber,
                Status = invoiceLine.Status.ToString()
            });
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Add Invoice line based on given InvoiceLineViewModel.
        /// </summary>
        /// <param name="model">InvoiceLineViewModel</param>
        /// <param name="createdBy">ApplicationUser that creates invoice line</param>
        /// <param name="recalculateInvoiceValues">Indicates if invoice line values should be recalculated based on price, tax rate, currency rate</param>
        /// <param name="recalculateBudgetValues">indicates if recalculation of budget invoiced amount should to be done</param>
        /// <returns>InvoiceLineReturnResult with line id, invoice id, line number and status</returns>
        public InvoiceLineReturnResult AddLine(InvoiceLineViewModel model, ApplicationUser createdBy, bool recalculateInvoiceValues, bool recalculateBudgetValues)
        {
            if (model == null || createdBy == null)
            {
                throw new ArgumentNullException(nameof(model), "Nieprawidłowe parametry");
            }

            var invoice = GetInvoiceById(model.InvoiceId, IncludeLevel.None);

            if (invoice == null)
            {
                throw new ArgumentException($"Faktura o podanym ID nie istnieje.", nameof(invoice));
            }

            if (invoice.Status == Status.Cancelled)
            {
                throw new InvalidOperationException("Fatura jest anulowana. Nie można dodawać nowych linii do anulowanej faktury");
            }

            decimal netto     = model.Netto;
            decimal tax       = model.Tax;
            decimal gross     = model.Gross;
            decimal baseNetto = model.BaseNetto;
            decimal baseTax   = model.BaseTax;
            decimal baseGross = model.BaseGross;

            if (recalculateInvoiceValues)
            {
                netto = model.Quantity * model.Price;
                tax   = model.Netto * (model.TaxRate / 100);
                gross = netto + tax;

                if (model.Currency.ToUpper() == "PLN")
                {
                    baseNetto = netto;
                    baseTax   = tax;
                    baseGross = gross;
                }
                else
                {
                    baseNetto = model.CurrencyRate == 0 ? 0 : netto * model.CurrencyRate;
                    baseTax   = baseNetto * (model.TaxRate / 100);
                    baseGross = baseNetto + baseTax;
                }
            }

            var now = DateHelper.GetCurrentDatetime();
            var invoiceLineNumber = GetNextInvoiceLineNum(model.InvoiceId);

            BudgetManager.UpdateBudgetInvoicedAmount(model.BudgetId, baseNetto, recalculateBudgetValues);

            var newInvoiceLine = new InvoiceLine()
            {
                Status       = Status.Opened,
                CreatedById  = createdBy.Id,
                CreatedDate  = now,
                InvoiceId    = model.InvoiceId,
                LineNumber   = invoiceLineNumber,
                ItemName     = model.ItemName,
                Description  = model.Description,
                Quantity     = model.Quantity,
                Price        = model.Price,
                Currency     = model.Currency,
                CurrencyRate = model.CurrencyRate,
                TaxRate      = model.TaxRate,
                Netto        = netto,
                Tax          = tax,
                Gross        = gross,
                BaseNetto    = baseNetto,
                BaseTax      = baseTax,
                BaseGross    = baseGross,
                BudgetId     = model.BudgetId
            };

            Context.InvoiceLines.Add(newInvoiceLine);
            var result = Context.SaveChanges();

            if (result == 0)
            {
                throw new Exception("Nie zapisano żadnych danych.");
            }

            return(new InvoiceLineReturnResult()
            {
                Id = newInvoiceLine.Id,
                InvoiceId = newInvoiceLine.InvoiceId,
                InvoiceNumber = invoice.InvoiceNumber,
                LineNumber = newInvoiceLine.LineNumber,
                Status = newInvoiceLine.Status.ToString()
            });
        }