using Casestudy.DAL.DomainClasses; using Casestudy.Helpers; using Castle.Components.DictionaryAdapter.Xml; using Microsoft.EntityFrameworkCore; namespace Casestudy.DAL.DAO { public class OrderDAO { private readonly AppDbContext _db; public OrderDAO(AppDbContext ctx) { _db = ctx; } public async Task<int> AddOrder(int customerId, OrderSelectionHelper[] selections) { int orderId = -1; using (var _trans = await _db.Database.BeginTransactionAsync()) { try { Order order = new(); order.CustomerId = customerId; order.OrderDate = DateTime.Now; order.OrderAmount = 0; await _db.Order!.AddAsync(order); await _db.SaveChangesAsync(); foreach (OrderSelectionHelper selection in selections) { OrderLineItem tItem = new(); tItem.QtyOrdered = selection.Qty; tItem.ProductId = selection.Product!.Id; tItem.OrderId = order.Id; var product = await _db.Products.FindAsync(tItem.ProductId); if (selection.Qty < product.QtyOnHand) { product.QtyOnHand -= selection.Qty; tItem.QtySold = selection.Qty; tItem.QtyBackOrdered = 0; } else { tItem.QtySold = product.QtyOnHand; tItem.QtyBackOrdered = selection.Qty - product.QtyOnHand; product.QtyOnBackOrder += tItem.QtyBackOrdered; product.QtyOnHand = 0; } tItem.SellingPrice = product.MSRP; order.OrderAmount += tItem.SellingPrice * tItem.QtySold; await _db.OrderLineItem!.AddAsync(tItem); await _db.SaveChangesAsync(); } await _trans.CommitAsync(); orderId = order.Id; } catch (Exception ex) { Console.WriteLine(ex.Message); await _trans.RollbackAsync(); } } return orderId; } public async Task<List<Order>> GetAll(int id) { return await _db.Order!.Where(order => order.CustomerId == id).ToListAsync<Order>(); } public async Task<List<OrderDetailsHelper>> GetOrderDetails(int tid, string email) { Customer? customer = _db.Customers!.FirstOrDefault(cus => cus.Email == email); List<OrderDetailsHelper> allDetails = new(); // LINQ way of doing INNER JOINS var results = from t in _db.Order join ti in _db.OrderLineItem! on t.Id equals ti.OrderId join mi in _db.Products! on ti.ProductId equals mi.Id where (t.CustomerId == customer!.Id && t.Id == tid) select new OrderDetailsHelper { OrderId = t.Id, CustomerId = customer!.Id, ProductName = mi.ProductName, ProductId = ti.ProductId, QtyOrdered = ti.QtyOrdered, QtySold = ti.QtySold, QtyBackOrdered = ti.QtyBackOrdered, SellingPrice = ti.SellingPrice, OrderDate = t.OrderDate.ToString("yyyy/MM/dd - hh:mm tt") }; allDetails = await results.ToListAsync(); return allDetails; } } }