public Result <string> BuyAll(int id) { var result = _context.BeginTransaction(() => { var prescription = _context.Prescriptions .Include(x => x.PrescriptionItems) .FirstOrDefault(x => x.Id == id); if (prescription == null) { throw new PrescriptionNotFoundException(id); } var items = prescription.PrescriptionItems.Where(x => !x.Status.Equals("BOUGHT")); var sb = new StringBuilder() .AppendLine("Szanowny kliencie,") .AppendLine($"Twoja recepta o numerze {prescription.Id} została właśnie wykupiona. Poniżej przedstawiamy kupione leki:"); var totalCost = 0.0M; foreach (var item in items) { var toBuy = item.QuantityToBuy - item.QuantityAlreadyBought; var stock = _context.DrugStoreAvailableMedicines.FirstOrDefault(x => x.MedicineId == item.MedicineId); if (stock == null) { throw new Exception($"Brakuje {toBuy} sztuk leku {item.Medicine.Name} o ID {item.MedicineId} na stanie apteki"); } if (stock.Quantity < toBuy) { throw new Exception($"Brakuje {toBuy - stock.Quantity} sztuk leku {item.Medicine.Name} o ID {item.MedicineId} na stanie apteki"); } sb.AppendLine($"\t{item.Medicine.Name} - ilość {item.QuantityToBuy}, cena jednostkowa {item.Medicine.UnitPrice:0.00} zł"); totalCost += item.QuantityToBuy * item.Medicine.UnitPrice; _context.Database.ExecuteSqlCommand("UPDATE PrescriptionItem SET QuantityAlreadyBought = QuantityToBuy WHERE Id = @id", new SqlParameter("id", item.Id)); _context.Database.ExecuteSqlCommand("UPDATE DrugStoreAvailableMedicine SET Quantity = (Quantity - @toBuy) WHERE MedicineId = @medId", new SqlParameter("toBuy", toBuy), new SqlParameter("medId", item.MedicineId)); } sb.AppendLine($"Całkowity koszt wyniósł {totalCost:0.00} zł") .AppendLine("Dziękujemy za zakupy i zapraszamy ponownie") .AppendLine() .AppendLine("Pozdrawiamy,") .AppendLine("Zespół iDrugs"); return(sb.ToString()); }, GetType()); return(result); }
public Result RemoveOrder(int id) { var result = _context.BeginTransaction(() => { var order = _context.Orders.Find(id); if (order == null) { throw new OrderNotFoundException(id); } foreach (var item in order.OrderItems.ToArray()) { _context.OrderItems.Remove(item); } _context.Orders.Remove(order); _context.SaveChanges(); }, typeof(OrderEfRepo)); return(result); }