public async Task <ProductEntryLineDto> Create(Guid userId, ProductEntryLineForCreationDto productEntryLineForCreationDto) { var product = await _productRepository.GetById(productEntryLineForCreationDto.ProductId); if (product == null) { throw new KeyNotFoundException($"Product with id: {productEntryLineForCreationDto.ProductId} not found."); } var productEntry = await _productEntryRepository.GetById(productEntryLineForCreationDto.ProductEntryId.Value); if (productEntry == null) { throw new KeyNotFoundException($"Product Entry with id: {productEntryLineForCreationDto.ProductEntryId.Value} not found."); } var productEntryLine = new ProductEntryLine() { Quantity = productEntryLineForCreationDto.Quantity, ProductId = productEntryLineForCreationDto.ProductId, ProductEntryId = productEntryLineForCreationDto.ProductEntryId.Value, CreatedBy = userId }; productEntryLine = await _productEntryLineRepository.Add(productEntryLine); product.Stock += productEntryLineForCreationDto.Quantity; await _productRepository.Update(product); await _productEntryLineRepository.CommitAsync(); await _productRepository.CommitAsync(); return(_mapper.Map <ProductEntryLine, ProductEntryLineDto>(productEntryLine)); }
public async Task <ProductEntryDto> Create(Guid userId, ProductEntryForCreationDto productEntryForCreationDto) { try { if (productEntryForCreationDto.IsEntry) { var vendor = await _vendorRepository.GetById(productEntryForCreationDto.VendorId.Value); if (vendor == null) { throw new KeyNotFoundException($"Vendor with id: {productEntryForCreationDto.VendorId.Value} not found."); } } ProductEntry productEntry = new ProductEntry() { Date = productEntryForCreationDto.Date.ToLocalTime(), IsEntry = productEntryForCreationDto.IsEntry, VendorId = productEntryForCreationDto.VendorId, Cost = productEntryForCreationDto.Cost, PaymentType = productEntryForCreationDto.PaymentType, Observations = productEntryForCreationDto.Observations, CreatedBy = userId }; productEntry = await _productEntryRepository.Add(productEntry); //ProductEntryLines foreach (var pelDto in productEntryForCreationDto.ProductEntryLines) { var product = await _productRepository.GetById(pelDto.ProductId); if (product == null) { throw new KeyNotFoundException($"Product with id: {pelDto.ProductId} not found."); } var productEntryLine = new ProductEntryLine() { Quantity = pelDto.Quantity, ProductId = pelDto.ProductId, ProductEntryId = productEntry.Id, CreatedBy = userId }; productEntryLine = await _productEntryLineRepository.Add(productEntryLine); productEntry.ProductEntryLines.Add(productEntryLine); product.Stock += pelDto.Quantity * (productEntry.IsEntry ? 1 : -1); await _productRepository.Update(product); } await _productEntryRepository.CommitAsync(); await _productEntryLineRepository.CommitAsync(); await _productRepository.CommitAsync(); var productEntryDto = _mapper.Map <ProductEntry, ProductEntryDto>(productEntry); return(productEntryDto); } catch (Exception e) { throw e; } }