Ejemplo n.º 1
0
        public async Task <ExpenseBillModel> Update(ExpenseBillModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            model.Validate();

            var bill = await _repository.LoadAsync <ExpenseBill>(model.Id);

            if (bill == null)
            {
                throw new ArgumentException($"Нет счета с Id = {model.Id}");
            }

            var oldsum       = bill.SumPrice;
            var oldAccountId = bill.AccountId;

            bill.DateTime      = model.DateTime;
            bill.SumPrice      = model.Cost;
            bill.ExpenseFlowId = model.ExpenseFlowId;
            bill.AccountId     = model.AccountId;

            foreach (var item in model.Items)
            {
                if (item.Id > 0 && !item.IsModified && !item.IsDeleted)
                {
                    continue;
                }
                if (item.Id <= 0 || item.IsModified)
                {
                    var itemModel = new ExpenseItem
                    {
                        BillId     = model.Id,
                        CategoryId = item.CategoryId,
                        ProductId  = item.ProductId,
                        Price      = item.Cost,
                        Quantity   = item.Quantity,
                        Comment    = item.Comment
                    };
                    if (item.Id <= 0)
                    {
                        _repository.Create(itemModel);
                    }
                    else
                    {
                        itemModel.Id = item.Id;
                        _repository.Update(itemModel);
                    }
                }
                else if (item.IsDeleted)
                {
                    var itemModel = await _repository.LoadAsync <ExpenseItem>(item.Id);

                    if (itemModel == null)
                    {
                        continue;
                    }
                    _repository.Delete(itemModel);
                }
            }

            _repository.Update(bill);

            var balance = await _transitionBalanceUpdater.Update(bill, oldsum, oldAccountId);

            await _transactionBuilder.UpdateExpense(bill, oldAccountId, balance);

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

            return(model);
        }