Пример #1
0
        public async Task <Data.Domains.Sales> SaveSalesAsync(SalesCommandReceived dto)
        {
            var products = await _stockService.GetAvailableStockProductAsync(dto.SoldItems);

            decimal totalAmountToPay = 0;

            Data.Domains.Sales  salesToSave      = new();
            List <SalesDetails> salesItemsToSave = new();

            if (!await _dbContext.Customers.AnyAsync(c => c.Id == dto.CustomerId))
            {
                salesToSave.Customer = new Customer
                {
                    Id     = dto.CustomerId,
                    Email  = dto.Email,
                    Mobile = dto.Mobile,
                    Name   = dto.CustomerName,
                };
                await _dbContext.Customers.AddAsync(salesToSave.Customer);
            }

            dto.SoldItems.ForEach(c =>
            {
                var productToUpdate = products.FirstOrDefault(p => p.Id == c.ProductId);
                var price           = productToUpdate.Price * c.Qty;
                totalAmountToPay   += price;
                salesItemsToSave.Add(new SalesDetails
                {
                    Price     = price,
                    ProductId = c.ProductId,
                    Qty       = c.Qty
                });
                c.ProductName             = productToUpdate.Name;
                productToUpdate.HoldQty  -= c.Qty;
                productToUpdate.StockQty -= c.Qty;
                _dbContext.Products.Update(productToUpdate);
            });

            salesToSave.CustomerId   = dto.CustomerId;
            salesToSave.TotalPrice   = totalAmountToPay;
            salesToSave.CustomerId   = dto.CustomerId;
            salesToSave.SoldAt       = DateTimeOffset.UtcNow;
            salesToSave.Reference    = dto.Reference;
            salesToSave.SalesDetails = salesItemsToSave;

            await _dbContext.Sales.AddAsync(salesToSave);

            await _dbContext.SaveChangesAsync();

            return(salesToSave);
        }
Пример #2
0
        public async Task <IActionResult> Sale([FromBody] SalesCommandReceived dto)
        {
            var isValidStock = await _mediator.Send(new AvailableStockQueryDto { SoldItems = dto.SoldItems });

            if (!isValidStock)
            {
                throw new BadRequestException("Sorry, Out of Stock!");
            }

            await _publishEndpoint.Publish(dto);

            await _redisCacheClient.RemoveAsync($"sales");

            return(Accepted());
        }