public async Task <ActionResult> Add([FromBody] PaymentAddRequest request) { LoggedUser loggedUser = LoggedUser; try { await UnitOfWork.ExecuteTransactionAsync(async (transaction, timeout) => { Payment payment = new Payment { InboxId = request.InboxId, UserId = loggedUser.UserId, TotalAmount = request.Amount, Note = request.Note }; UnitOfWork.PaymentRepository.Add(payment); await UnitOfWork.SaveChangesAsync(); IEnumerable <Expense> expensesNotPaid = await UnitOfWork.ExpenseRepository.GetNotPaidExpensesByInboxIdAsync(request.InboxId); decimal totalPayment = payment.TotalAmount; foreach (Expense expense in expensesNotPaid) { if (totalPayment <= 0) { break; } decimal amountToPay = expense.TotalAmount - expense.CurrentAmount; decimal paidAmount = totalPayment >= amountToPay ? amountToPay : totalPayment; totalPayment -= paidAmount; expense.CurrentAmount += paidAmount; ExpensePayment expensePayment = new ExpensePayment { PaymentId = payment.Id, ExpenseId = expense.Id, Amount = paidAmount }; UnitOfWork.ExpenseRepository.Update(expense); UnitOfWork.ExpensePaymentRepository.Add(expensePayment); } payment.CurrentAmount = payment.TotalAmount - totalPayment; UnitOfWork.PaymentRepository.Update(payment); await UnitOfWork.SaveChangesAsync(); }, null, null); return(Ok()); } catch (Exception ex) { return(InternalServerError(ex.InnerExceptionMessage())); } }
public async Task <ActionResult> Add([FromBody] ExpenseAddRequest request) { LoggedUser loggedUser = LoggedUser; try { Expense expense = new Expense { InboxId = request.InboxId, UserId = loggedUser.UserId, Name = request.Name, TotalAmount = request.Amount, Note = request.Note }; IEnumerable <Payment> availableResources = await UnitOfWork.PaymentRepository.GetAvailableResourcesByInboxIdAsync(request.InboxId); decimal totalAmount = request.Amount; foreach (Payment payment in availableResources) { if (totalAmount <= 0) { break; } decimal availablePayment = payment.TotalAmount - payment.CurrentAmount; decimal paidAmount = availablePayment >= totalAmount ? totalAmount : availablePayment; totalAmount -= paidAmount; payment.CurrentAmount += paidAmount; ExpensePayment expensePayment = new ExpensePayment { PaymentId = payment.Id, ExpenseId = expense.Id, Amount = paidAmount }; UnitOfWork.PaymentRepository.Update(payment); UnitOfWork.ExpensePaymentRepository.Add(expensePayment); } UnitOfWork.ExpenseRepository.Add(expense); await UnitOfWork.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { return(InternalServerError(ex.InnerExceptionMessage())); } }
public CommandResult AddDebit(ExpensePayment expensePayment) { if (expensePayment.Status == Paid) { var balance = Balance -= expensePayment.Value; if (balance < 0) { return(new Exception("Insufficient balance!")); } Balance = balance; } Debts.Add(expensePayment); return(CommandResult.Success()); }