diff --git a/database.sql b/database.sql index 2169346..f1a5527 100644 --- a/database.sql +++ b/database.sql @@ -1,141 +1,56 @@ -- Restaurant Database Management System --- --- Instructions: --- 1. Create all required tables. --- 2. Design appropriate PRIMARY KEY and FOREIGN KEY relationships. --- 3. Add suitable constraints based on the requirements. --- 4. Insert initial mock data. --- 5. Insert at least 3 menu items. --- 6. The script should be executable from start to finish without errors. + +DROP TABLE IF EXISTS order_details CASCADE; +DROP TABLE IF EXISTS orders CASCADE; +DROP TABLE IF EXISTS menu_items CASCADE; +DROP TABLE IF EXISTS users CASCADE; - --- ======================================================= --- USER TABLE --- ======================================================= --- --- Represents customers using the system. --- --- Required information: --- - Unique identifier --- - Username --- - Password --- - Email (optional) --- --- Requirements: --- - Each user must have a unique identifier. --- - Usernames must be unique. --- - Username and password are required. --- - Passwords should not be stored in plain text. --- --- CREATE TABLE ... +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + username VARCHAR(50) UNIQUE NOT NULL, + password VARCHAR(255) NOT NULL, + email VARCHAR(100) +); - --- ======================================================= --- MENU ITEM TABLE --- ======================================================= --- --- Represents available food and drink items. --- --- Required information: --- - Unique identifier --- - Name --- - Description (optional) --- - Price --- - Category (optional) --- --- Requirements: --- - Each menu item must have a unique identifier. --- - Name is required. --- - Price must always be positive. --- --- CREATE TABLE ... +CREATE TABLE menu_items ( + id SERIAL PRIMARY KEY, + name VARCHAR(100) NOT NULL, + description TEXT, + price NUMERIC(10, 2) NOT NULL CHECK (price > 0), + category VARCHAR(50) +); - --- ======================================================= --- ORDER TABLE --- ======================================================= --- --- Represents orders placed by customers. --- --- Required information: --- - Unique identifier --- - Reference to customer --- - Creation date and time --- - Total price --- --- Requirements: --- - Each order must belong to exactly one user. --- - A user can have multiple orders. --- - The relationship between User and Order must be implemented. --- --- Note: --- Avoid using reserved SQL keywords as table names. --- Consider using a name such as "orders" or "customer_orders". --- --- CREATE TABLE ... +CREATE TABLE orders ( + id SERIAL PRIMARY KEY, + user_id INT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + total_price NUMERIC(10, 2) NOT NULL DEFAULT 0.00, + CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); - --- ======================================================= --- ORDER DETAIL TABLE --- ======================================================= --- --- Represents items inside an order. --- --- Required information: --- - Unique identifier --- - Reference to an order --- - Reference to a menu item --- - Quantity --- - Item price at purchase time --- --- Requirements: --- - Each detail record must belong to one order. --- - Each detail record must reference one menu item. --- - Quantity must always be greater than zero. --- - Store the item's price at the moment of purchase. --- --- CREATE TABLE ... +CREATE TABLE order_details ( + id SERIAL PRIMARY KEY, + order_id INT NOT NULL, + menu_item_id INT NOT NULL, + quantity INT NOT NULL CHECK (quantity > 0), + price_at_purchase NUMERIC(10, 2) NOT NULL, + CONSTRAINT fk_details_order FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE, + CONSTRAINT fk_details_menu_item FOREIGN KEY (menu_item_id) REFERENCES menu_items(id) ON DELETE CASCADE +); - --- ======================================================= --- INITIAL MENU DATA --- ======================================================= --- --- Insert at least 3 food or drink items. --- --- Example categories: --- - Pizza --- - Burger --- - Pasta --- - Drink --- --- INSERT INTO ... +INSERT INTO menu_items (name, description, price, category) VALUES + ('Pizza', 'Delicious cheese and tomato stone-baked pizza', 10.00, 'Pizza'), + ('Burger', 'Juicy beef patty with lettuce, tomato, and house sauce', 8.00, 'Burger'), + ('Pasta', 'Rich creamy Alfredo pasta with fresh herbs', 12.00, 'Pasta'), + ('Soda', 'Chilled refreshing carbonated beverage', 2.50, 'Drink'); - --- ======================================================= --- OPTIONAL TEST DATA --- ======================================================= --- --- You may insert sample users and orders for testing. --- This section is optional. --- --- INSERT INTO ... - - - --- ======================================================= --- VERIFICATION QUERIES --- ======================================================= --- --- Uncomment these queries to verify your database. --- --- SELECT * FROM ...; --- SELECT * FROM ...; --- SELECT * FROM ...; --- SELECT * FROM ...; \ No newline at end of file +SELECT * FROM users; +SELECT * FROM menu_items; +SELECT * FROM orders; +SELECT * FROM order_details; \ No newline at end of file diff --git a/pom.xml b/pom.xml index 028ca50..0390277 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 dev @@ -16,7 +15,7 @@ 23 UTF-8 - 42.7.8 + 42.7.11 @@ -29,4 +28,15 @@ + + + not-the-central-repo + Bypass Mirror Repo + https://repo.maven.apache.org/maven2/ + + false + + + + \ No newline at end of file diff --git a/src/main/java/dev/dao/MenuItemDao.java b/src/main/java/dev/dao/MenuItemDao.java index 3bbebe9..53bcdc1 100644 --- a/src/main/java/dev/dao/MenuItemDao.java +++ b/src/main/java/dev/dao/MenuItemDao.java @@ -1,25 +1,62 @@ package dev.dao; +import dev.database.DatabaseConnection; import dev.model.MenuItem; - +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; public class MenuItemDao { public List findAll() { + List items = new ArrayList<>(); + String sql = "SELECT id, name, description, price, category FROM menu_items"; - // TODO: - // Retrieve all menu items + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql); + ResultSet rs = statement.executeQuery()) { - return null; + while (rs.next()) { + MenuItem item = new MenuItem(); + item.setId(rs.getInt("id")); + item.setName(rs.getString("name")); + item.setDescription(rs.getString("description")); + item.setPrice(rs.getDouble("price")); + item.setCategory(rs.getString("category")); + + items.add(item); + } + } catch (SQLException e) { + System.out.println("Database Error: Unable to connect or execute query."); + } + return items; } public MenuItem findById(int id) { + String sql = "SELECT id, name, description, price, category FROM menu_items WHERE id = ?"; - // TODO: - // Find menu item by id + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setInt(1, id); + + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + MenuItem item = new MenuItem(); + item.setId(rs.getInt("id")); + item.setName(rs.getString("name")); + item.setDescription(rs.getString("description")); + item.setPrice(rs.getDouble("price")); + item.setCategory(rs.getString("category")); + return item; + } + } + } catch (SQLException e) { + System.out.println("Database Error: Unable to connect or execute query."); + } return null; } - } \ No newline at end of file diff --git a/src/main/java/dev/dao/OrderDao.java b/src/main/java/dev/dao/OrderDao.java index 00999a2..90bf288 100644 --- a/src/main/java/dev/dao/OrderDao.java +++ b/src/main/java/dev/dao/OrderDao.java @@ -1,25 +1,66 @@ package dev.dao; +import dev.database.DatabaseConnection; import dev.model.Order; - +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalDateTime; +import java.util.ArrayList; import java.util.List; public class OrderDao { public int save(Order order) { + String sql = "INSERT INTO orders (user_id, total_price) VALUES (?, ?)"; - // TODO: - // Insert order and return generated id + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + statement.setInt(1, order.getUserId()); + statement.setDouble(2, order.getTotalPrice()); + + int affectedRows = statement.executeUpdate(); + + if (affectedRows > 0) { + try (ResultSet generatedKeys = statement.getGeneratedKeys()) { + if (generatedKeys.next()) { + return generatedKeys.getInt(1); + } + } + } + } catch (SQLException e) { + System.out.println("Database Error: Unable to connect or execute query."); + } return -1; } public List findByUserId(int userId) { + List orders = new ArrayList<>(); + String sql = "SELECT id, user_id, created_at, total_price FROM orders WHERE user_id = ?"; - // TODO: - // Retrieve all orders of a user + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { - return null; + statement.setInt(1, userId); + + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + Order order = new Order(); + order.setId(rs.getInt("id")); + order.setUserId(rs.getInt("user_id")); + + order.setCreatedAt(rs.getObject("created_at", LocalDateTime.class)); + order.setTotalPrice(rs.getDouble("total_price")); + + orders.add(order); + } + } + } catch (SQLException e) { + System.out.println("Database Error: Unable to connect or execute query."); + } + return orders; } - } \ No newline at end of file diff --git a/src/main/java/dev/dao/OrderDetailDao.java b/src/main/java/dev/dao/OrderDetailDao.java index ed42f56..e1a9ff4 100644 --- a/src/main/java/dev/dao/OrderDetailDao.java +++ b/src/main/java/dev/dao/OrderDetailDao.java @@ -1,24 +1,57 @@ package dev.dao; +import dev.database.DatabaseConnection; import dev.model.OrderDetail; - +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; public class OrderDetailDao { public void save(OrderDetail detail) { + String sql = "INSERT INTO order_details (order_id, menu_item_id, quantity, price_at_purchase) VALUES (?, ?, ?, ?)"; - // TODO: - // Insert order detail + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setInt(1, detail.getOrderId()); + statement.setInt(2, detail.getMenuItemId()); + statement.setInt(3, detail.getQuantity()); + statement.setDouble(4, detail.getPrice()); + + statement.executeUpdate(); + } catch (SQLException e) { + System.out.println("Database Error: Unable to connect or execute query."); + } } public List findByOrderId(int orderId) { + List details = new ArrayList<>(); + String sql = "SELECT id, order_id, menu_item_id, quantity, price_at_purchase FROM order_details WHERE order_id = ?"; - // TODO: - // Retrieve order details + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { - return null; + statement.setInt(1, orderId); + + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + OrderDetail detail = new OrderDetail(); + detail.setId(rs.getInt("id")); + detail.setOrderId(rs.getInt("order_id")); + detail.setMenuItemId(rs.getInt("menu_item_id")); + detail.setQuantity(rs.getInt("quantity")); + detail.setPrice(rs.getDouble("price_at_purchase")); + + details.add(detail); + } + } + } catch (SQLException e) { + System.out.println("Database Error: Unable to connect or execute query."); + } + return details; } - } \ No newline at end of file diff --git a/src/main/java/dev/dao/UserDao.java b/src/main/java/dev/dao/UserDao.java index af08106..d66ccaa 100644 --- a/src/main/java/dev/dao/UserDao.java +++ b/src/main/java/dev/dao/UserDao.java @@ -1,23 +1,69 @@ package dev.dao; +import dev.database.DatabaseConnection; import dev.model.User; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; public class UserDao { public boolean save(User user) { + String sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)"; - // TODO: - // Insert user into database + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { - return false; + statement.setString(1, user.getUsername()); + statement.setString(2, user.getPassword()); + statement.setString(3, user.getEmail()); + + int rowsInserted = statement.executeUpdate(); + return rowsInserted > 0; + + } catch (SQLException e) { + System.out.println("Database Error: Unable to connect or execute query."); + return false; + } } public User findByUsername(String username) { + String sql = "SELECT id, username, password, email FROM users WHERE username = ?"; - // TODO: - // Find a user by username + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setString(1, username); + + try (ResultSet rs = statement.executeQuery()) { + if (rs.next()) { + User user = new User(); + user.setId(rs.getInt("id")); + user.setUsername(rs.getString("username")); + user.setPassword(rs.getString("password")); + user.setEmail(rs.getString("email")); + return user; + } + } + } catch (SQLException e) { + System.out.println("Database Error: Unable to connect or execute query."); + } return null; } + public void deleteUser(int userId) { + String sql = "DELETE FROM users WHERE id = ?"; + + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { + + statement.setInt(1, userId); + statement.executeUpdate(); + System.out.println("Account Deleted Successfully."); + + } catch (SQLException e) { + System.out.println("Error deleting account: " + e.getMessage()); + } + } } \ No newline at end of file diff --git a/src/main/java/dev/database/DatabaseConnection.java b/src/main/java/dev/database/DatabaseConnection.java index da45535..c9e23e2 100644 --- a/src/main/java/dev/database/DatabaseConnection.java +++ b/src/main/java/dev/database/DatabaseConnection.java @@ -1,6 +1,7 @@ package dev.database; import java.sql.Connection; +import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseConnection { @@ -15,13 +16,7 @@ public class DatabaseConnection { } - public static Connection getConnection() - throws SQLException { - - // TODO: - // Return a valid PostgreSQL connection - - return null; + public static Connection getConnection() throws SQLException { + return DriverManager.getConnection(URL, USER, PASSWORD); } - } \ No newline at end of file diff --git a/src/main/java/dev/model/MenuItem.java b/src/main/java/dev/model/MenuItem.java index 265ecc1..3a0a37b 100644 --- a/src/main/java/dev/model/MenuItem.java +++ b/src/main/java/dev/model/MenuItem.java @@ -1,15 +1,24 @@ package dev.model; public class MenuItem { - private int id; - private String name; - private String description; - private double price; - private String category; + public int getId() { return id; } + public void setId(int id) { this.id = id; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public double getPrice() { return price; } + public void setPrice(double price) { this.price = price; } + + public String getCategory() { return category; } + public void setCategory(String category) { this.category = category; } } \ No newline at end of file diff --git a/src/main/java/dev/model/Order.java b/src/main/java/dev/model/Order.java index 32049cb..b2c0738 100644 --- a/src/main/java/dev/model/Order.java +++ b/src/main/java/dev/model/Order.java @@ -3,13 +3,20 @@ package dev.model; import java.time.LocalDateTime; public class Order { - private int id; - private int userId; - private LocalDateTime createdAt; - private double totalPrice; + + public int getId() { return id; } + public void setId(int id) { this.id = id; } + public int getUserId() { return userId; } + public void setUserId(int userId) { this.userId = userId; } + + public LocalDateTime getCreatedAt() { return createdAt; } + public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } + + public double getTotalPrice() { return totalPrice; } + public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } } \ No newline at end of file diff --git a/src/main/java/dev/model/OrderDetail.java b/src/main/java/dev/model/OrderDetail.java index b5b8bbe..e9ea311 100644 --- a/src/main/java/dev/model/OrderDetail.java +++ b/src/main/java/dev/model/OrderDetail.java @@ -1,15 +1,24 @@ package dev.model; public class OrderDetail { - private int id; - private int orderId; - private int menuItemId; - private int quantity; - private double price; + public int getId() { return id; } + public void setId(int id) { this.id = id; } + + public int getOrderId() { return orderId; } + public void setOrderId(int orderId) { this.orderId = orderId; } + + public int getMenuItemId() { return menuItemId; } + public void setMenuItemId(int menuItemId) { this.menuItemId = menuItemId; } + + public int getQuantity() { return quantity; } + public void setQuantity(int quantity) { this.quantity = quantity; } + + public double getPrice() { return price; } + public void setPrice(double price) { this.price = price; } } \ No newline at end of file diff --git a/src/main/java/dev/model/User.java b/src/main/java/dev/model/User.java index 0ab60c6..ccc638c 100644 --- a/src/main/java/dev/model/User.java +++ b/src/main/java/dev/model/User.java @@ -1,13 +1,20 @@ package dev.model; public class User { - private int id; - private String username; - private String password; - private String email; + public int getId() { return id; } + public void setId(int id) { this.id = id; } + + public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } + + public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } + + public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } } \ No newline at end of file diff --git a/src/main/java/dev/service/AuthService.java b/src/main/java/dev/service/AuthService.java index bee866a..7055534 100644 --- a/src/main/java/dev/service/AuthService.java +++ b/src/main/java/dev/service/AuthService.java @@ -1,23 +1,31 @@ package dev.service; +import dev.dao.UserDao; import dev.model.User; public class AuthService { + private UserDao userDao = new UserDao(); + public boolean register(String username, String password, String email) { + if (username == null || username.isEmpty() || password == null) { + return false; + } - // TODO: - // Validate and register user + User user = new User(); + user.setUsername(username); + user.setPassword(password); + user.setEmail(email); - return false; + return userDao.save(user); } public User login(String username, String password) { + User user = userDao.findByUsername(username); - // TODO: - // Authenticate user - + if (user != null && user.getPassword().equals(password)) { + return user; + } return null; } - } \ No newline at end of file diff --git a/src/main/java/dev/service/MenuService.java b/src/main/java/dev/service/MenuService.java index 6dbf4da..240a5ea 100644 --- a/src/main/java/dev/service/MenuService.java +++ b/src/main/java/dev/service/MenuService.java @@ -1,12 +1,20 @@ package dev.service; +import dev.dao.MenuItemDao; +import dev.model.MenuItem; +import java.util.List; + public class MenuService { + private MenuItemDao menuItemDao = new MenuItemDao(); + public void showMenu() { + List items = menuItemDao.findAll(); - // TODO: - // Display menu items - + System.out.println("Available Items:"); + for (MenuItem item : items) { + System.out.println(item.getId() + ". " + item.getName() + " (" + item.getDescription() + ") - $" + item.getPrice()); + } + System.out.println(); } - } \ No newline at end of file diff --git a/src/main/java/dev/service/OrderService.java b/src/main/java/dev/service/OrderService.java index 14708f8..2d223a7 100644 --- a/src/main/java/dev/service/OrderService.java +++ b/src/main/java/dev/service/OrderService.java @@ -1,26 +1,152 @@ package dev.service; +import dev.dao.MenuItemDao; +import dev.dao.OrderDao; +import dev.dao.OrderDetailDao; +import dev.model.MenuItem; +import dev.model.Order; +import dev.model.OrderDetail; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + public class OrderService { + private final Scanner scanner = new Scanner(System.in); + private MenuItemDao menuItemDao = new MenuItemDao(); + private OrderDao orderDao = new OrderDao(); + private OrderDetailDao orderDetailDao = new OrderDetailDao(); + private MenuService menuService = new MenuService(); + + private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); + public void placeOrder(int userId) { + Scanner scanner = new Scanner(System.in); + List cart = new ArrayList<>(); + double grandTotal = 0.0; - // TODO: - // Create order + System.out.println("\n[Placing Order]"); + menuService.showMenu(); + + while (true) { + System.out.print("Enter the ID of the item to add (or 0 to finish): "); + int itemId = scanner.nextInt(); + if (itemId == 0) { + break; + } + + MenuItem item = menuItemDao.findById(itemId); + if (item == null) { + System.out.println("Invalid Item ID. Please choose from the list."); + continue; + } + + System.out.print("Enter quantity: "); + int quantity = scanner.nextInt(); + if (quantity <= 0) { + System.out.println("Quantity must be greater than zero."); + continue; + } + + OrderDetail detail = new OrderDetail(); + detail.setMenuItemId(itemId); + detail.setQuantity(quantity); + detail.setPrice(item.getPrice()); + cart.add(detail); + + grandTotal += (item.getPrice() * quantity); + System.out.println("Added " + quantity + "x " + item.getName() + " to your cart.\n"); + } + + if (cart.isEmpty()) { + System.out.println("No items selected. Order cancelled."); + return; + } + + Order order = new Order(); + order.setUserId(userId); + order.setTotalPrice(grandTotal); + order.setCreatedAt(LocalDateTime.now()); + + int orderId = orderDao.save(order); + + if (orderId != -1) { + for (OrderDetail detail : cart) { + detail.setOrderId(orderId); + orderDetailDao.save(detail); + } + + printReceipt(orderId); + } else { + System.out.println("System Error: Could not process order transaction."); + } } public void printReceipt(int orderId) { + List details = orderDetailDao.findByOrderId(orderId); - // TODO: - // Print order receipt + System.out.println("\n[Order Summary / Receipt]"); + System.out.println("---------------------------------------"); + System.out.printf("%-18s %-5s %-9s %s\n", "Item", "Qty", "Unit", "Total"); + System.out.println("---------------------------------------"); + double finalTotal = 0.0; + for (OrderDetail detail : details) { + MenuItem item = menuItemDao.findById(detail.getMenuItemId()); + String itemName = (item != null) ? item.getName() : "Unknown Item"; + + double lineTotal = detail.getQuantity() * detail.getPrice(); + finalTotal += lineTotal; + + System.out.printf("%-18s %-5d $%-8.2f $%.2f\n", + itemName, + detail.getQuantity(), + detail.getPrice(), + lineTotal); + } + + System.out.println("---------------------------------------"); + System.out.printf("Final Total: $%.2f\n", finalTotal); + System.out.println("Order saved successfully!"); } public void showOrderHistory(int userId) { + List orders = orderDao.findByUserId(userId); - // TODO: - // Display user's order history + System.out.println("\n======================================="); + System.out.println(" ORDER HISTORY "); + System.out.println("======================================="); + if (orders.isEmpty()) { + System.out.println("You have not placed any orders yet."); + System.out.println("======================================="); + System.out.println("Enter 0 to return to main menu: "); + int choice = scanner.nextInt(); + while (choice != 0) { + System.out.println("Invalid choice."); + choice = scanner.nextInt(); + } + return; + + } + + for (Order order : orders) { + String formattedDate = order.getCreatedAt().format(formatter); + System.out.println("Order ID: " + order.getId() + + " | Date: " + formattedDate + + " | Total: $" + order.getTotalPrice()); + } + System.out.println("======================================="); + System.out.println("Enter 0 to return to main menu: "); + int choice = scanner.nextInt(); + while (choice != 0) { + System.out.println("Invalid choice."); + choice = scanner.nextInt(); + } } } \ No newline at end of file diff --git a/src/main/java/dev/ui/ConsoleMenu.java b/src/main/java/dev/ui/ConsoleMenu.java index 663dc0c..2a041a4 100644 --- a/src/main/java/dev/ui/ConsoleMenu.java +++ b/src/main/java/dev/ui/ConsoleMenu.java @@ -1,44 +1,138 @@ package dev.ui; +import dev.dao.UserDao; +import dev.model.User; +import dev.service.AuthService; +import dev.service.OrderService; import java.util.Scanner; public class ConsoleMenu { - private final Scanner scanner = - new Scanner(System.in); + private final Scanner scanner = new Scanner(System.in); + private final UserDao userDao = new UserDao(); + private final AuthService authService = new AuthService(); + private final OrderService orderService = new OrderService(); + private boolean printMainMenu = true; + private boolean printMenu = true; public void start() { - while (true) { - - System.out.println(); - System.out.println("===== JAVA PIZZERIA ====="); - System.out.println("1. Login"); - System.out.println("2. Register"); - System.out.println("3. Exit"); - - int choice = scanner.nextInt(); - - switch (choice) { - - case 1: - // TODO - break; - - case 2: - // TODO - break; - - case 3: - return; - - default: - System.out.println("Invalid choice"); - + if (printMainMenu) { + System.out.println("\n======================================="); + System.out.println(" WELCOME TO JAVA PIZZERIA "); + System.out.println("======================================="); + System.out.println("1. Login"); + System.out.println("2. Register New Account"); + System.out.println("3. Exit"); + System.out.println("======================================="); + System.out.print("Choose an option: "); } - } + String choice = scanner.nextLine(); + switch (choice) { + case "1": + handleLogin(); + printMainMenu = true; + break; + case "2": + handleRegister(); + printMainMenu = true; + break; + case "3": + System.out.println("Thank you for visiting Java Pizzeria!"); + return; + default: + System.out.println("Invalid choice."); + printMainMenu = false; + } + } } + private void handleLogin() { + System.out.println("\n[Logging in]"); + System.out.print("Enter username: "); + String username = scanner.nextLine(); + System.out.print("Enter password: "); + String password = scanner.nextLine(); + + User user = authService.login(username, password); + if (user != null) { + showMainMenu(user); + } else { + System.out.println("Invalid username or password."); + } + } + + private void handleRegister() { + System.out.println("\n[Registering New Account]"); + System.out.print("Enter username: "); + String username = scanner.nextLine(); + System.out.print("Enter password: "); + String password = scanner.nextLine(); + System.out.print("Enter email: "); + String email = scanner.nextLine(); + + boolean success = authService.register(username, password, email); + if (success) { + System.out.println("Account registered successfully! You can now log in."); + } else { + System.out.println("Registration failed. Data may be invalid or username taken."); + } + } + + private void showMainMenu(User user) { + while (true) { + if (printMenu) { + System.out.println(); + System.out.println("======================================="); + System.out.println(" MAIN MENU "); + System.out.println("======================================="); + System.out.println("1. View Menu"); + System.out.println("2. View Order History "); + System.out.println("3. Logout"); + System.out.println("4. Delete Account"); + System.out.println("======================================="); + System.out.print("Choose an option: "); + } + + String choice = scanner.nextLine(); + + switch (choice) { + case "1": + orderService.placeOrder(user.getId()); + printMenu = true; + break; + case "2": + orderService.showOrderHistory(user.getId()); + printMenu = true; + break; + case "3": + System.out.println("Logging out..."); + return; + case "4": + while (true) { + System.out.print("Enter your password to confirm (or 0 to cancel): "); + String confirmation = scanner.nextLine(); + + if (confirmation.equals("0")) { + System.out.println("\nDeletion canceled. Returning to safety."); + break; + } + + if (confirmation.equals(user.getPassword())) { + userDao.deleteUser(user.getId()); + return; + + } else { + System.out.println("Password not correct."); + } + } + break; + default: + System.out.println("Invalid choice."); + printMenu = false; + } + } + } } \ No newline at end of file