public string GetOrderHistoryByCustomer(int id) { // This method is called because we need the information on the whole catalog // Since the catalog is small I went with this implementation. // If it was much large I would only fill the library with the relevant books FillBookLibrary(); // Attempt to find the customer CustomerEntity dbCustomer = _context.Customers .Include(o => o.Orders) .ThenInclude(ol => ol.Orderlines) .FirstOrDefault(c => c.Id == id); // If the customer was not found then let the user know if (dbCustomer == null) { return("No Customer exists by this name."); } string result = ""; // if one was found then map it to a usable object Library.Models.Customer m_customer = Mapper_Customer.MapCustomerWithOrders(dbCustomer); // Build the string that needs to be returned result += m_customer; foreach (Library.Models.Order order in m_customer.Orders) { result += $"\n{order}"; } return(result); }
/// <summary> /// Update the details of a customer /// </summary> /// <param name="customer">Business-Model customer object</param> /// <param name="firstName">new first name, remains unchanged if null</param> /// <param name="lastName">new last name, remains unchanged if null</param> /// <param name="email">new email address, remains unchanged if null</param> public void UpdateCustomer(Library.Models.Customer customer, string firstName, string lastName, string email) { var dbCustomer = _dbContext.Customers.First(c => c.Id == customer.Id); dbCustomer.FirstName = firstName ?? dbCustomer.FirstName; dbCustomer.LastName = lastName ?? dbCustomer.LastName; dbCustomer.Email = email ?? dbCustomer.Email; }
public static Models.Customer MapLibCustomer(Library.Models.Customer customer) { return(new Models.Customer() { //CustomerId = customer.customerID, FirstName = customer.FirstName, LastName = customer.LastName, //Orders = customer.OrderHistory.Select(LibOrdersMap).ToList() }); }
/// <summary> /// This turns a customer Model into a customer entity, by assigning each relavent property /// to a column in the customer table /// </summary> /// <param name="customer">The customer model.</param> /// <returns></returns> public static Entities.CustomerEntity Map(Library.Models.Customer customer) { return(new Entities.CustomerEntity { FirstName = customer.FirstName, LastName = customer.LastName, Id = customer.ID, LocationId = customer.MyStoreLocation.ID }); }
/// <summary> /// Turn a model customer with their location into a entity customer /// </summary> /// <param name="customer"></param> /// <returns></returns> public static Entities.CustomerEntity MapCustomerWithLocation(Library.Models.Customer customer) { return(new Entities.CustomerEntity { FirstName = customer.FirstName, LastName = customer.LastName, Id = customer.ID, Location = Mapper_Location.Map(customer.MyStoreLocation) }); }
/// <summary> /// Retrieve all orders in the database submitted by a particular customer /// </summary> /// <returns>A list of Business-Model order objects</returns> public List <Library.Models.Order> GetCustomerOrders(Library.Models.Customer customer) { var dbOrders = _dbContext.Orders .Where(o => o.CustomerId == customer.Id) .OrderByDescending(o => o.Date).ToList(); List <Library.Models.Order> orders = new List <Library.Models.Order>(); foreach (var order in dbOrders) { orders.Add(GetOrderById(order.Id)); } return(orders); }
/// <summary> /// Retrieve Business-Model order object from database via order id /// </summary> /// <param name="id">Order id</param> /// <returns>Business-Model order object</returns> public Library.Models.Order GetOrderById(int id) { var dbOrder = _dbContext.Orders .Include(o => o.Location) .Include(o => o.Customer) .Include(o => o.OrderContents) .ThenInclude(oc => oc.Product) .FirstOrDefault(o => o.Id == id); if (dbOrder is null) { return(null); } var location = new Library.Models.Location( dbOrder.Location.Name, dbOrder.Location.Address, dbOrder.Location.City, dbOrder.Location.State, dbOrder.Location.Country, dbOrder.Location.PostalCode, dbOrder.Location.Phone ) { Id = dbOrder.LocationId }; var customer = new Library.Models.Customer() { Id = dbOrder.CustomerId, FirstName = dbOrder.Customer.FirstName, LastName = dbOrder.Customer.LastName, Email = dbOrder.Customer.Email }; Dictionary <int, int> products = new Dictionary <int, int>(); Dictionary <int, decimal> prices = new Dictionary <int, decimal>(); foreach (OrderContent oc in dbOrder.OrderContents) { products.Add(oc.ProductId, oc.Quantity); prices.Add(oc.ProductId, oc.Price); } return(new Library.Models.Order() { Id = dbOrder.Id, Products = products, PricePaid = prices, Customer = customer, Location = location, Time = dbOrder.Date }); }
// // Adding Methods // /// <summary> /// Add a new customer to the database /// </summary> /// <param name="customer">Business-Model customer object</param> public void AddCustomer(Library.Models.Customer customer) { if (customer.Id != 0) // IDs are assigned by database, so it already exists if not 0 { throw new ArgumentException("Customer already exists."); } var dbCustomer = new Customer() { FirstName = customer.FirstName, LastName = customer.LastName, Email = customer.Email }; _dbContext.Customers.Add(dbCustomer); }
/// <summary> /// Add a new Customer from Models to Database. /// </summary> /// <param name="customer"> This is the new Model to be put into the database. It only has a firstname and last name.</param> public void AddACustomer(Library.Models.Customer customer) { // Create the Entity item to be put into the database CustomerEntity entity = new CustomerEntity(); // Since the database handles the ID setting with identity, we only need to assign the new entity the firstname and the lastname // Maybe in the future we could add a way to change the location, but for now the database sets the location to the default 1. entity.FirstName = customer.FirstName; entity.LastName = customer.LastName; entity.Id = 0; // Add the new entity to the context to send over to the database _context.Add(entity); // I am using the aproach of sending the data over after each change instead of having a universal save button Save(); }
public IActionResult AddCustomer(CustomerViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } try { Library.Models.Customer customer = new Library.Models.Customer(viewModel.FirstName, viewModel.LastName); _customerRepo.Add(customer); customer = _customerRepo.SearchCustomerByName(viewModel.FirstName); TempData["CustomerID"] = customer.customerID; return(RedirectToAction(nameof(ViewDetails), new { id = customer.customerID })); } catch (Exception) { ModelState.AddModelError("", "there was some error, try again."); return(View()); } }
/// <summary> /// Right now this is mainly a helper method when placing the order. This is because this returns a Library.Models.Customer object /// That is manipulated by the c# code. The intention was to get the Customer and then set the location and it's inventory /// </summary> /// <param name="name">Two strings that are valid names.</param> /// <returns></returns> public Library.Models.Customer GetCustomerWithLocationAndInventory(int id) { // first we create our db customer to check if we find it CustomerEntity dbCustomer = new CustomerEntity(); try { // if we do then we assign it to the customer dbCustomer = _context.Customers.Include(l => l.Location).First(c => c.Id == id); } catch (InvalidOperationException ex) { // if we don't then we return null return(null); } // since we found it we map the new customer with the location Library.Models.Customer m_customer = Mapper_Customer.MapCustomerWithLocation(dbCustomer); // then we get the stocks for the location m_customer.MyStoreLocation.Inventory = GetStocksForLocation(m_customer.MyStoreLocation.ID); return(m_customer); }
// // Deletion Methods // public void RemoveCustomer(Library.Models.Customer customer) { throw new NotImplementedException(); }
static void Main(string[] args) { var saveLocation = "../../../../json.txt"; string input; List <PizzaStore> stores; List <Orders> orders; List <Library.Models.Customer> customers; //List<Inventory> storeInventory; var dataSource = new List <PizzaStore>(); //for initializing repo var optionsBuilder = new DbContextOptionsBuilder <project0Context>(); optionsBuilder.UseSqlServer(secretConfiguration.ConnectionString); //pass options builder what sql server to use and login info var options = optionsBuilder.Options; var dbContext = new project0Context(options); var storeRepository = new PizzaStoreRepository(dbContext); var orderRepository = new OrderRepo(dbContext); var customerRepository = new CustomerRepo(dbContext); //var inventoryRepository = new InventoryRepo(dbContext); //testing serialization worked with multiple stores //storeRepository.AddStore(new PizzaStore()); //storeRepository.AddStore(new PizzaStore()); while (true) //loop until exit command given { Console.WriteLine("p:\tDisplay or modify pizza stores."); Console.WriteLine("a:\tTo add pizza store."); Console.WriteLine("c:\tDisplay or add customers."); //Console.WriteLine("o:\tTo place order"); Console.WriteLine("s:\tSave data to disk."); //Console.WriteLine("l:\tLoad data from disk."); Console.Write("Enter valid menu option, or \"exit\" to quit: "); input = Console.ReadLine(); //read command from console if (input == "p") //still need other use cases { while (true) { DisplayOrModifyStores(); input = Console.ReadLine(); if (input == "b") { break; } else if (int.TryParse(input, out var storeNum) && storeNum > 0 && storeNum <= stores.Count) //if input is a valid store number { while (true) { //display chosen stores info var store = stores[storeNum - 1]; var storeString = $"ID: {store.Id}, Name: \"{store.Name}\""; //storeString += ", at Location: " + store.Location.ToString(); Console.WriteLine(storeString); Console.WriteLine(); Console.WriteLine("o:\tDisplay orders."); Console.WriteLine("i:\tDisplay or modify inventory"); Console.Write("Enter valid menu option, or b to go back: "); input = Console.ReadLine(); if (input == "b") { break; } else if (input == "o") { DisplayOrdersOfStore(store.Id); } else if (input == "i") { if (store.Inventory == null) { Console.WriteLine("No inventory."); } else { Console.WriteLine("Inventory: "); foreach (var item in store.Inventory) { Console.WriteLine($"Item Name: \"{item.Key}\", " + $"Item Quantity: \"{item.Value}\""); } } while (true) { Console.WriteLine("a:\tAdd inventory item."); Console.Write("Enter valid menu option, or b to go back: "); input = Console.ReadLine(); if (input == "a") { Dictionary <string, int> inv = store.Inventory; AddInventoryItem(ref inv); store.Inventory = inv; storeRepository.UpdateStore(store); } else if (input == "b") { break; } } } } } else { Console.WriteLine(); Console.WriteLine($"Invalid input \"{input}\"."); Console.WriteLine(); } } } else if (input == "a") { AddNewPizzaStore(); } else if (input == "c") { while (true) { DisplayAddOrModifyCustomers(); input = Console.ReadLine(); if (input == "b") { break; } else if (input == "a") { AddNewCustomer(); } else if (int.TryParse(input, out var custNum) && custNum > 0 && custNum <= customers.Count) //if input is a valid store number { while (true) { //display chosen stores info var cust = customers[custNum - 1]; var custString = $"ID: {cust.Id}, Name: \"{cust.FirstName} {cust.LastName}\""; Console.WriteLine(custString); Console.WriteLine("c:\tModify customer"); Console.Write("Enter valid menu option, or b to go back: "); input = Console.ReadLine(); if (input == "b") { break; } else if (input == "c") { ////Modify Customer!!!!!!! } } } } } //else if (input == "o") //{ //} else if (input == "s") //use serializer to save data to file { SaveToFile(); } //else if (input == "l") //loading data from file //{ // LoadFromFile(); //} else if (input == "exit") //exits loop and therefore program { break; } else { Console.WriteLine(); Console.WriteLine($"Invalid input \"{input}\"."); Console.WriteLine(); } } void DisplayAddOrModifyCustomers() { customers = customerRepository.GetAllCustomer().ToList(); Console.WriteLine(); if (customers.Count == 0) { Console.WriteLine("No customers."); } else { for (var i = 1; i <= customers.Count; i++) { var customer = customers[i - 1]; //indexing starts at 0 var custString = $"{i}: \"{customer.FirstName} {customer.LastName}\" "; //storeString += $", at Location: {store.Location.ToString()}"; Console.WriteLine(custString); } } Console.WriteLine("a:\tAdd customer."); Console.WriteLine(); Console.WriteLine("Enter valid menu option, or \"b\" to go back: "); } void DisplayOrModifyStores() { stores = storeRepository.GetStores().ToList(); Console.WriteLine(); if (stores.Count == 0) { Console.WriteLine("No pizza stores."); } for (var i = 1; i <= stores.Count; i++) { var store = stores[i - 1]; //indexing starts at 0 var storeString = $"{i}: \"{store.Name}\""; //storeString += $", at Location: {store.Location.ToString()}"; Console.WriteLine(storeString); } Console.WriteLine(); Console.WriteLine("Enter valid menu option, or \"b\" to go back: "); } void DisplayOrdersOfStore(int id) { orders = orderRepository.GetOrdersOfLocation(id).ToList(); Console.WriteLine(); if (orders.Count == 0) { Console.WriteLine("No orders."); } for (var i = 1; i <= orders.Count; i++) { var order = orders[i - 1]; //indexing starts at 0 var ordString = $"{i}: Store\\: \"{order.StoreId}\", Customer\\: " + $"\"{order.CustomerId}\", Time\\: \"{order.OrderTime}"; Console.WriteLine(ordString); } } PizzaStore AddNewPizzaStore() { Console.WriteLine(); string name = null; //Library.Models.Address address = null; Dictionary <string, int> inventory = null; while (true) { Console.Write("Would you like to use the default name? (y/n)"); input = Console.ReadLine(); if (input == "y") { break; } else if (input == "n") { Console.Write("Enter the new pizza restaurant's name: "); name = Console.ReadLine(); break; } } //while (true) //{ // Console.Write("Would you like to use a default location? (y/n)"); // input = Console.ReadLine(); // if (input == "y") // { // break; // } // else if (input == "n") // { // address = NewAddress(); // break; // } //} while (true) { Console.Write("Would you like to use the default inventory? (y/n)"); input = Console.ReadLine(); if (input == "y") { break; } else if (input == "n") { inventory = NewInventory(); break; } } //PizzaStore restaurant = new PizzaStore(name, inventory, address); PizzaStore restaurant = new PizzaStore(name, inventory); storeRepository.AddStore(restaurant); return(restaurant); } void AddNewCustomer() { Console.WriteLine(); Console.Write("Enter the new customer's firstname: "); string firstname = Console.ReadLine(); Console.Write("Enter the new customer's lastname: "); string lastname = Console.ReadLine(); PizzaStore store; while (true) { Console.Write("Would you like to use the default store? (y/n)"); input = Console.ReadLine(); if (input == "y") { store = new PizzaStore(); break; } else if (input == "n") { while (true) { Console.Write("Would you like to use a new store? (y/n)"); input = Console.ReadLine(); if (input == "y") { store = AddNewPizzaStore(); break; } else if (input == "n") { Console.Write("Enter existing store id: "); input = Console.ReadLine(); store = storeRepository.GetStoreById(Convert.ToInt32(input)); break; } } break; } } Library.Models.Customer cust = new Library.Models.Customer(firstname, lastname, store); customerRepository.AddCustomer(cust); } void AddInventoryItem(ref Dictionary <string, int> inv) { Console.WriteLine("Enter the new item's name: "); string name = Console.ReadLine(); Console.WriteLine("Enter the new item's amount: "); int amount = Convert.ToInt32(Console.ReadLine()); inv.Add(name, amount); Console.WriteLine("Added"); } Dictionary <string, int> NewInventory() { Dictionary <string, int> inventory = new Dictionary <string, int>(); while (true) { Console.Write("Would you like to add an inventory item? (y/n)"); input = Console.ReadLine(); if (input == "y") { try { AddInventoryItem(ref inventory); } catch (ArgumentException e) { //log it Console.WriteLine(e.Message); return(inventory); } } else if (input == "n") { break; } } return(inventory); } //Library.Models.Address NewAddress() //{ // string street, city, state, zipcode, country; // Console.Write("Enter the new pizza restaurant's location - street: "); // street = Console.ReadLine(); // Console.Write("Enter the new pizza restaurant's location - city: "); // city = Console.ReadLine(); // Console.Write("Enter the new pizza restaurant's location - state: "); // state = Console.ReadLine(); // Console.Write("Enter the new pizza restaurant's location - zipcode: "); // zipcode = Console.ReadLine(); // Console.Write("Enter the new pizza restaurant's location - country: "); // country = Console.ReadLine(); // try // { // return new Library.Models.Address(street, city, state, zipcode, country); // } // catch (ArgumentException ex) // { // Console.WriteLine(ex.Message); // } // return null; //} void SaveToFile() { Console.WriteLine(); stores = storeRepository.GetStores().ToList(); //get list of all pizza stores try { var serialized = JsonConvert.SerializeObject(stores, Formatting.Indented); //serialize to the file File.WriteAllTextAsync(saveLocation, serialized); Console.WriteLine("Saving Success."); } catch (SecurityException ex) { Console.WriteLine($"Error while saving: {ex.Message}"); } catch (IOException ex) { Console.WriteLine($"Error while saving: {ex.Message}"); } //other exceptions } //void LoadFromFile() //{ // Console.WriteLine(); // try // { // var deserialized = new List<PizzaStore>(); // deserialized = JsonConvert.DeserializeObject<List<PizzaStore>>(File.ReadAllText(saveLocation)); // if (deserialized != null) // { // deserialized.ToList(); // } // Console.WriteLine("Loading Success."); // var allStores = storeRepository.GetAllStores().ToList(); // foreach (var item in allStores) //delete current repo one restaraunt at a time // { // //try // //{ // storeRepository.DeleteStore(item); //throws error! // //} // //catch (ArgumentOutOfRangeException e) // //{ // // Console.WriteLine(e.Message); // //} // } // if (deserialized != null) // { // foreach (var item in deserialized) //replace with repo data from file // { // storeRepository.AddStore(item); // } // } // } // catch (FileNotFoundException) //if no save file // { // Console.WriteLine("No saved data found."); // } // catch (SecurityException ex) // { // Console.WriteLine($"Error while loading: {ex.Message}"); // } // catch (IOException ex) // { // Console.WriteLine($"Error while loading: {ex.Message}"); // } // //other exceptions? //} }