예제 #1
0
        public async Task <int> Create(ExpenseBillModel model, bool correction = false)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            model.Validate();

            var bill = new ExpenseBill
            {
                ExpenseFlowId = model.ExpenseFlowId,
                AccountId     = model.AccountId,
                DateTime      = model.DateTime,
                SumPrice      = model.Cost,
                OwnerId       = _currentSession.UserId,
                IsCorrection  = correction,
            };

            model.IsCorection = correction;

            _repository.Create(bill);

            foreach (var item in model.Items)
            {
                _repository.Create(new ExpenseItem
                {
                    Bill       = bill,
                    CategoryId = item.CategoryId,
                    ProductId  = item.ProductId,
                    Price      = item.Cost,
                    Quantity   = item.Quantity,
                    Comment    = item.Comment
                });
            }

            Account account = null;

            if (model.AccountId != null)
            {
                account = await _repository.LoadAsync <Account>(model.AccountId.Value);
            }

            if (account != null)
            {
                var balancesUpdater = _balancesUpdaterFactory.Create(account.AccountType);
                await balancesUpdater.Create(account, bill).ConfigureAwait(false);

                _transactionBuilder.CreateExpense(bill, account.Balance);
            }

            await _repository.SaveChangesAsync().ConfigureAwait(false);

            model.Id = bill.Id;
            return(model.Id);
        }