public async Task Should_register_bill() { var command = RegisterBillCommandFake.Default(); var defaultUser = new IdentityUser { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true }; _userManager.FindByIdAsync(Arg.Any <string>()).Returns(defaultUser); _billRepository.AddAsync(Arg.Any <Bill>()).Returns(true); var cancelationToken = CancellationToken.None; var expected = new CommandResponse { Message = "Conta registrada com sucesso", Sucess = true }; var result = await _commandHandler.Handle(command, cancelationToken); result.Sucess.Should().Be(expected.Sucess); }
public async Task<BillViewModel> Create(BillViewModel billVm) { try { //var order = Mapper.Map<BillViewModel, Bill>(billVm); var order = new BillViewModel().Map(billVm); // var orderDetails = Mapper.Map<List<BillDetailViewModel>, List<BillDetail>>(billVm.BillDetails); var orderDetails = new BillDetailViewModel().Map(billVm.BillDetails.AsParallel().AsOrdered().WithDegreeOfParallelism(3)).ToList(); foreach (var detail in orderDetails) { var product =await _productRepository.FindById(detail.ProductId); detail.Price = product.Price; } order.BillDetails = orderDetails; var billEntity = await _orderRepository.AddAsync(order); return new BillViewModel().Map(billEntity); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task <BillViewModel> Create(BillViewModel billVm) { try { var bill = new Bill(billVm.CustomerName, billVm.CustomerAddress, billVm.CustomerMobile, billVm.CustomerMessage, billVm.BillStatus, billVm.PaymentMethod, billVm.Status, billVm.CustomerId); bill.AddBillDetails(new BillDetailViewModel().Map(billVm.BillDetails).ToList()); await _orderRepository.AddAsync(bill); _unitOfWork.Commit(); return(new BillViewModel().Map(bill)); } catch (Exception e) { Console.WriteLine(e); throw; } }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <bool> Handle(CreateBillCommand request, CancellationToken cancellationToken) { var bill = new Bill(request.Person); await _repository.AddAsync(bill, cancellationToken); await _repository.UnitOfWork.SaveEntitiesAsync(cancellationToken); //var address = new Address("1", "2", "3", "4", "5"); //var order = new Order("1", "ycp", address, 1, "2", "2", "2", DateTime.Now); //order.AddOrderItem(1, "abc", 10, 2, "http://www.baidu.com"); //await _orderRepository.AddAsync(order); //await _orderRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); return(true); }
public async Task <CommandResponse> Handle(RegisterBillCommand command, CancellationToken cancellationToken) { if (!command.IsValid(_serviceProvider)) { return new CommandResponse { ValidationResult = command.ValidationResult, Sucess = false } } ; var user = await _userManager.FindByIdAsync(command.UserId); if (user == null) { return new CommandResponse { ValidationResult = command.ValidationResult, Sucess = false, Message = "Usuario não encontrado" } } ; var bill = _mapper.Map <Bill>(command); bill.AddUser(user); var result = await _billRepository.AddAsync(bill); if (!result) { AddError("Houve um erro ao persistir os dados"); return(new CommandResponse { ValidationResult = ValidationResult, Sucess = false }); } return(new CommandResponse { Message = "Conta registrada com sucesso", Sucess = true }); } } }
public async Task <Bill> CreateAndSplitBillAsync(CreateNewBill newBillData) { newBillData.Validate(); var group = await groupRepository.GetByIdAsync(newBillData.GroupContextId); if (group == null) { throw new NotFoundException($"Group with id {newBillData.GroupContextId} does not exist."); } var loaner = group.Users.FirstOrDefault(user => user.Id == newBillData.LoanerId); if (loaner == null) { throw new NotFoundException($"Payee with id {newBillData.LoanerId} does not exist in group."); } var bill = new Bill() { Name = newBillData.Name, Total = newBillData.Total, LoanerId = loaner.Id, Loaner = loaner, GroupContextId = group.Id, GroupContext = group, }; bill = await billRepository.AddAsync(bill); var loans = SplitBill(bill); loans.ForEach(loan => bill.Loans.Add(loan)); await billRepository.SaveChangesAsync(); return(bill); }
public async Task AddAsync(BillAddModel model) { //var items = (await _itemRepository.GetAsync(model.Items)).ToList(); //model.TotalAmount = items.Sum(x => x.Rate); //model.Tax = items.Where(x => x.IsTaxable).Sum(x => x.Rate * x.SalesTax.TaxPercentage / 100); //var vendor = await _vendorRepository.GetAsync(model.VendorId); //if (vendor.Discount != null) //{ // model.Discount = model.TotalAmount * vendor.Discount / 100; // model.TotalAmount = model.TotalAmount - (model.Discount ?? 0); //} //if (model.Tax != null) //{ // model.TotalAmount = model.TotalAmount + (model.Tax ?? 0); //} model.LineAmountSubTotal = model.Items.Sum(x => x.LineAmount); var count = await _repository.getCount(); var bill = BillFactory.Create(model, _userId, count); await _repository.AddAsync(bill); await _unitOfWork.SaveChangesAsync(); var transaction = TransactionFactory.CreateByBill(bill); await _transactionRepository.AddAsync(transaction); await _unitOfWork.SaveChangesAsync(); var itemsList = (model.Items.GroupBy(l => l.BankAccountId, l => new { l.BankAccountId, l.LineAmount }) .Select(g => new { GroupId = g.Key, Values = g.ToList() })).ToList(); foreach (var item in itemsList) { var id = item.GroupId; var amount = item.Values.Sum(x => x.LineAmount); var itemsData = TransactionFactory.CreateByBillItemsAndTax(bill, id, amount); await _transactionRepository.AddAsync(itemsData); await _unitOfWork.SaveChangesAsync(); } var taxlistList = (model.Items.GroupBy(l => l.TaxBankAccountId, l => new { l.TaxBankAccountId, l.TaxPrice }) .Select(g => new { GroupId = g.Key, Values = g.ToList() })).ToList(); foreach (var tax in taxlistList) { if (tax.GroupId > 0) { var id = tax.GroupId; var amount = tax.Values.Sum(x => x.TaxPrice); var taxData = TransactionFactory.CreateByBillItemsAndTax(bill, id, amount); await _transactionRepository.AddAsync(taxData); await _unitOfWork.SaveChangesAsync(); } } }
public async Task <IActionResult> Post(long typeId, [FromBody] AddBillViewModel model) { if (model == null) { return(BadRequest()); } if (typeId != model.BillTypeId) { return(BadRequest()); } if (_periodManager.GetPeriod() == Guid.Empty) { ModelState.AddModelError("", Resources.Global.Common.FinancialPeriodMustBeSpecified); return(BadRequest(ModelState.GetWithErrorsKey())); } var financialPeriod = await _financialPeriodRepo.FindAsync(_periodManager.GetPeriod()); if (financialPeriod == null) { return(NotFound("FinancialPeriodNotFound")); } if (!financialPeriod.CheckIfDateInPeriod(model.Date)) { ModelState.AddModelError("Date", Resources.Global.Common.DateOutCurrenctPeriod); return(BadRequest(ModelState.GetWithErrorsKey())); } var billType = await _billTypeRepo.GetAsync(typeId); if (billType == null) { return(NotFound(Resources.Bills.BillResource.BillTypeNotFound)); } switch (billType.Type) { case BillsType.Transfer: ModelState.AddModelError("", "can't not add new transfare from here!"); return(BadRequest(ModelState.GetWithErrorsKey())); case BillsType.EndPeriodInventory: ModelState.AddModelError("", "can't add End Period Inventory bill"); return(BadRequest(ModelState.GetWithErrorsKey())); } #region checks Guid currencyId; var currency = await _currencyRepo.GetAsync(model.CurrencyId); if (currency != null) { currencyId = currency.Id; if (!model.CurrencyValue.HasValue) { model.CurrencyValue = currency.Value; } } else { currencyId = _defaultKeysOptions.Value.CurrencyId; model.CurrencyValue = 1; } Guid cashAccountId; var cashAccount = await _accountRepo.GetAsync(model.AccountId); if (cashAccount == null) { return(NotFound("Cash account not found")); } cashAccountId = cashAccount.Id; Guid?customerAccountId = null; if (model.CustomerAccountId.HasValue) { var customerAccount = await _accountRepo.GetAsync(model.CustomerAccountId.Value); if (customerAccount == null) { return(NotFound("Customer account not found")); } if (customerAccount.CustomerId == null) { ModelState.AddModelError("CustomerAccountId", "account not related to customer or supplier"); return(BadRequest(ModelState.GetWithErrorsKey())); } customerAccountId = customerAccount.Id; } Guid?storeId = null; if (model.StoreId.HasValue) { var store = await _storeRepo.GetAsync(model.StoreId.Value); if (store == null) { return(NotFound(Resources.Stores.StoreResource.StoreNotFound)); } storeId = store.Id; } Guid?costCenterId = null; if (model.CostCenterId.HasValue) { var costCenter = await _costCenterRepo.GetAsync(model.CostCenterId.Value); if (costCenter == null) { return(NotFound(Resources.CostCenters.CostCenterResource.CostCenterNotFound)); } costCenterId = costCenter.Id; } Guid?branchId = null; if (model.BranchId.HasValue) { var branch = await _branchRepo.GetAsync(model.BranchId.Value); if (branch == null) { return(NotFound(Resources.Branchs.BranchResource.BranchNotFound)); } branchId = branch.Id; } #endregion var bill = new Bill(billType.Id, currencyId, model.CurrencyValue.Value, cashAccountId, customerAccountId, model.CustomerName, model.Date, model.PayType, storeId, costCenterId, branchId, model.Extra, model.Disc, model.TotalPaid, model.Note); // add the payemnt if (bill.PayType == PaysType.Credit && billType.DefaultCashAccountId.HasValue) { double credit = 0; double debit = 0; var inOrOut = int.Parse(EnumHelper.GetDescription(billType.Type)); if (inOrOut == 1) { // مشتريات credit = bill.TotalPaid; // صندوق debit = 0; // مورد } else { // مبيعات credit = 0; // زبون debit = bill.TotalPaid; // صندوق } var payEntryItem = new BillEntryItem(bill.Date, billType.DefaultCashAccountId.Value, bill.CurrencyId, bill.CurrencyValue, null, BillEntryItemType.Pay, debit, credit, ""); bill.BillEntryItems.Add(payEntryItem); } var itemsIndex = 0; // check form items if not found foreach (var item in model.Items) { itemsIndex++; Guid itemStoreId; if (model.StoreId.HasValue && model.StoreId.Value == item.StoreId) { itemStoreId = storeId.Value; } else { var itemStore = await _storeRepo.GetAsync(item.StoreId.Value); if (itemStore == null) { return(NotFound($"store in item {itemsIndex} not found")); } itemStoreId = itemStore.Id; } Guid?itemCostCenterId = null; if (model.CostCenterId.HasValue && item.CostCenterId.HasValue && model.CostCenterId == item.CostCenterId) { itemCostCenterId = costCenterId; } else { if (item.CostCenterId.HasValue) { var itemCostCenter = await _storeRepo.GetAsync(item.CostCenterId.Value); if (itemCostCenter == null) { return(NotFound($"costCenter in item {0} not found")); } } } var itemUnit = _itemUnitRepo.Get(item.ItemId, item.UnitId); if (itemUnit == null) { ModelState.AddModelError($"Items[{itemsIndex}].ItemId", "المادة غير موجودة"); return(BadRequest(ModelState.GetWithErrorsKey())); } var billItem = new BillItem(itemUnit.Id, itemStoreId, itemCostCenterId, item.Quantity, item.Price, item.Extra, item.Disc, model.Note); bill.BillItems.Add(billItem); if (billType.AutoPostToStores) { if (!await PostToStore(bill, billType, billItem, itemUnit)) { ModelState.AddModelError($"Items[{itemsIndex}].Quantity", "لا يوجد كل هذه الكمية في المستودع"); return(BadRequest(ModelState.GetWithErrorsKey())); } bill.IsPosted = true; } } bill.CalcTotal(); #region billEntryItem if (bill.Extra + bill.TotalItemsExtra > 0 && billType.DefaultExtraAccountId.HasValue) { var extraEntryItem = new BillEntryItem(bill.Date, billType.DefaultExtraAccountId.Value, bill.CurrencyId, bill.CurrencyValue, bill.CostCenterId, BillEntryItemType.ExtraDisc, 0, bill.Extra + bill.TotalItemsExtra, bill.Note); bill.BillEntryItems.Add(extraEntryItem); } if (bill.Disc + bill.TotalItemsDisc > 0 && billType.DefaultDiscAccountId.HasValue) { var discEntryItem = new BillEntryItem(bill.Date, billType.DefaultDiscAccountId.Value, bill.CurrencyId, bill.CurrencyValue, bill.CostCenterId, BillEntryItemType.ExtraDisc, bill.Disc + bill.TotalItemsDisc, 0, bill.Note); bill.BillEntryItems.Add(discEntryItem); } foreach (var pay in model.Pays) { var payEntryItem = new BillEntryItem(pay.Date, pay.AccountId, pay.CurrencyId, pay.CurrencyValue, pay.CostCenterId, BillEntryItemType.Pay, pay.Debit, pay.Credit, pay.Note); bill.BillEntryItems.Add(payEntryItem); } #endregion if (billType.AutoGenerateEntry) { if (bill.PayType == PaysType.Cash) { bill.AccountId = cashAccountId; } else { bill.AccountId = customerAccountId; } Entry entry = GenerateEntry(bill, billType); bill.BillEntry = new BillEntry(entry); _entryRepo.Add(entry, false); bill.IsEntryGenerated = true; if (billType.AutoPostEntryToAccounts) { await _accountBalanceService.PostEntryToAccounts(entry); } } bill.Number = await _billRepo.GetNextNumberAsync(billType.Id); var affectedRows = await _billRepo.AddAsync(bill); if (affectedRows > 0) { var viewModel = AutoMapper.Mapper.Map <BillViewModel>(bill); return(CreatedAtRoute("GetBill", new { typeId = bill.BillType.Number, id = bill.Number }, viewModel)); } return(BadRequest()); }