Ejemplo n.º 1
0
        public async Task <ResultOrError <ExpenseModel> > Handle(AddExpenseParameters input)
        {
            if (!await _context.DoesExist <User>(input.UserId))
            {
                return(CommonErrors.UserNotExist);
            }

            if (input.ExpenseTypeId.HasValue && !await _context.DoesExist <ExpenseType>(input.ExpenseTypeId.Value))
            {
                return(ExpenseTypeNotExist);
            }

            Expense newExpense;
            var     aggregateId = input.AggregateId;

            if (aggregateId.HasValue)
            {
                if (!await _context.ExpensesAggregates.AnyAsync(x => x.Id == input.AggregateId.Value))
                {
                    return(CommonErrors.ExpenseAggregateNotFound);
                }
            }
            else
            {
                var aggregate = ExpensesAggregate.Create(input.UserId, input.Name, input.AddedDate, isDraft: false);
                await _context.ExpensesAggregates.AddAsync(aggregate);

                aggregateId = aggregate.Id;
            }

            newExpense = Expense.Create(input.Name, input.Amount, aggregateId.Value, input.ExpenseTypeId);
            await _context.Expenses.AddAsync(newExpense);

            await _context.SaveChangesAsync();

            return(newExpense.ToModel());
        }