Example #1
0
        public async Task <IOperationResult> HandleAsync(IUpdateSaleBasedStockOperation command, ICorrelationContext context)
        {
            var stockOp = await _repository.GetAsync(command.Id);

            if (stockOp is null)
            {
                throw new BaristaException("stock_operation_not_found", $"Could not find stock operation with ID '{command.Id}'");
            }
            if (!(stockOp is Domain.SaleBasedStockOperation saleBasedStockOp))
            {
                throw new BaristaException("invalid_stock_operation_update_command", $"The stock operation with ID '{command.Id}' is not a sale-based stock operation and therefore cannot be updated with this command.");
            }

            await Task.WhenAll(
                _stockItemVerifier.AssertExists(command.StockItemId),
                _saleVerifier.AssertExists(command.SaleId)
                );

            saleBasedStockOp.SetQuantity(command.Quantity);
            saleBasedStockOp.SetStockItem(command.StockItemId);
            saleBasedStockOp.SetSaleId(command.SaleId);

            await _repository.UpdateAsync(saleBasedStockOp);

            await _repository.SaveChanges();

            await _busPublisher.Publish(new SaleBasedStockOperationUpdated(saleBasedStockOp.Id, saleBasedStockOp.StockItemId, saleBasedStockOp.Quantity, saleBasedStockOp.SaleId));

            return(OperationResult.Ok());
        }
        public async Task <IIdentifierResult> HandleAsync(ICreateSaleBasedStockOperation command, ICorrelationContext context)
        {
            await Task.WhenAll(
                _stockItemVerifier.AssertExists(command.StockItemId),
                _saleVerifier.AssertExists(command.SaleId)
                );

            var saleBasedStockOp = new Domain.SaleBasedStockOperation(command.Id, command.StockItemId, command.Quantity, command.SaleId);
            await _repository.AddAsync(saleBasedStockOp);

            try
            {
                await _repository.SaveChanges();
            }
            catch (EntityAlreadyExistsException)
            {
                throw new BaristaException("sale_based_stock_operation_already_exists", $"A sale-based stock operation with the ID '{command.Id}' already exists.");
            }


            await _busPublisher.Publish(new SaleBasedStockOperationCreated(saleBasedStockOp.Id, saleBasedStockOp.StockItemId, saleBasedStockOp.Quantity, saleBasedStockOp.SaleId));

            return(new IdentifierResult(saleBasedStockOp.Id));
        }