diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..ab1f416 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..bf2c501 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..aa00ffa --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..4158879 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..eba6e1f --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/database.sql b/database.sql index 2169346..3a6ce82 100644 --- a/database.sql +++ b/database.sql @@ -1,141 +1,85 @@ --- 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. - - - -- ======================================================= -- 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) NOT NULL UNIQUE, + 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 +-- ORDERS 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, + 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_order_details_order + FOREIGN KEY (order_id) + REFERENCES orders(id) + ON DELETE CASCADE, + + CONSTRAINT fk_order_details_menu_item + FOREIGN KEY (menu_item_id) + REFERENCES menu_items(id) +); -- ======================================================= -- 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 + ('Margherita Pizza', 'Classic cheese pizza', 10.00, 'Pizza'), + ('Cheeseburger', 'Beef burger with cheese', 8.50, 'Burger'), + ('Spaghetti Bolognese', 'Pasta with meat sauce', 12.00, 'Pasta'), + ('Coca Cola', 'Cold soft drink', 2.50, 'Drink'); -- ======================================================= --- OPTIONAL TEST DATA +-- OPTIONAL TEST USER -- ======================================================= --- --- You may insert sample users and orders for testing. --- This section is optional. --- --- INSERT INTO ... - +INSERT INTO users (username, password, email) VALUES + ('admin', 'hashed_password_here', 'admin@example.com'); -- ======================================================= -- 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/src/main/java/dev/Main.java b/src/main/java/dev/Main.java index 3a93683..b883f75 100644 --- a/src/main/java/dev/Main.java +++ b/src/main/java/dev/Main.java @@ -1,14 +1,47 @@ package dev; +import dev.dao.MenuItemDao; +import dev.dao.OrderDao; +import dev.dao.OrderDetailDao; +import dev.dao.UserDao; +import dev.database.DatabaseConnection; +import dev.service.AuthService; +import dev.service.MenuService; +import dev.service.OrderService; import dev.ui.ConsoleMenu; -public class Main { +import java.sql.Connection; - public static void main(String[] args) { +public class Main +{ + public static void main(String[] args) + { + try + { + Connection connection = DatabaseConnection.getConnection(); - ConsoleMenu menu = new ConsoleMenu(); - menu.start(); + UserDao userDao = new UserDao(connection); + MenuItemDao menuItemDao = new MenuItemDao(connection); + OrderDao orderDao = new OrderDao(connection); + OrderDetailDao orderDetailDao = new OrderDetailDao(connection); + AuthService authService = new AuthService(userDao); + MenuService menuService = new MenuService(menuItemDao); + OrderService orderService = new OrderService( + orderDao, + orderDetailDao, + menuItemDao + ); + + ConsoleMenu menu = new ConsoleMenu( + authService, + menuService, + orderService + ); + + menu.start(); + + } + catch (Exception e) {System.out.println("Application error: " + e.getMessage());} } - } \ 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..04f3e51 100644 --- a/src/main/java/dev/dao/MenuItemDao.java +++ b/src/main/java/dev/dao/MenuItemDao.java @@ -2,24 +2,72 @@ package dev.dao; import dev.model.MenuItem; +import java.sql.*; +import java.util.ArrayList; import java.util.List; -public class MenuItemDao { +public class MenuItemDao +{ + private final Connection connection; - public List findAll() { + public MenuItemDao(Connection connection) {this.connection = connection;} - // TODO: - // Retrieve all menu items + public List findAll() + { + List items = new ArrayList<>(); + + String sql = "SELECT id, name, description, price, category FROM menu_items"; + + try (PreparedStatement ps = connection.prepareStatement(sql); + ResultSet rs = ps.executeQuery()) + { + 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("Error fetching menu items: " + e.getMessage());} + + return items; + } + + public MenuItem findById(int id) + { + String sql = "SELECT id, name, description, price, category FROM menu_items WHERE id = ?"; + + try (PreparedStatement ps = connection.prepareStatement(sql)) + { + + ps.setInt(1, id); + + try (ResultSet rs = ps.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("Error finding menu item: " + e.getMessage());} return null; } - - public MenuItem findById(int id) { - - // TODO: - // Find menu item by id - - 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..76271cf 100644 --- a/src/main/java/dev/dao/OrderDao.java +++ b/src/main/java/dev/dao/OrderDao.java @@ -2,24 +2,77 @@ package dev.dao; import dev.model.Order; +import java.sql.*; +import java.util.ArrayList; import java.util.List; -public class OrderDao { +public class OrderDao +{ + private final Connection connection; - public int save(Order order) { + public OrderDao(Connection connection) {this.connection = connection;} - // TODO: - // Insert order and return generated id + public int save(Order order) + { + String sql = """ + INSERT INTO orders (user_id, created_at, total_price) + VALUES (?, ?, ?) + """; + + try (PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) + { + ps.setInt(1, order.getUserId()); + ps.setTimestamp(2, Timestamp.valueOf(order.getCreatedAt())); + ps.setDouble(3, order.getTotalPrice()); + + int affectedRows = ps.executeUpdate(); + + if (affectedRows == 0) {return -1;} + + try (ResultSet generatedKeys = ps.getGeneratedKeys()) + { + if (generatedKeys.next()) {return generatedKeys.getInt(1);} + } + + } + catch (SQLException e) {System.out.println("Error saving order: " + e.getMessage());} return -1; } - public List findByUserId(int userId) { + public List findByUserId(int userId) + { + List orders = new ArrayList<>(); - // TODO: - // Retrieve all orders of a user + String sql = """ + SELECT id, user_id, created_at, total_price + FROM orders + WHERE user_id = ? + ORDER BY created_at DESC + """; - return null; + try (PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setInt(1, userId); + + try (ResultSet rs = ps.executeQuery()) + { + while (rs.next()) + { + Order order = new Order(); + + order.setId(rs.getInt("id")); + order.setUserId(rs.getInt("user_id")); + order.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime()); + order.setTotalPrice(rs.getDouble("total_price")); + + orders.add(order); + } + } + + } + catch (SQLException e) {System.out.println("Error fetching orders: " + e.getMessage());} + + 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..d291ff6 100644 --- a/src/main/java/dev/dao/OrderDetailDao.java +++ b/src/main/java/dev/dao/OrderDetailDao.java @@ -2,23 +2,69 @@ package dev.dao; import dev.model.OrderDetail; +import java.sql.*; +import java.util.ArrayList; import java.util.List; -public class OrderDetailDao { +public class OrderDetailDao +{ + private final Connection connection; - public void save(OrderDetail detail) { + public OrderDetailDao(Connection connection) {this.connection = connection;} - // TODO: - // Insert order detail + public void save(OrderDetail detail) + { + String sql = """ + INSERT INTO order_details (order_id, menu_item_id, quantity, price_at_purchase) + VALUES (?, ?, ?, ?) + """; + try (PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setInt(1, detail.getOrderId()); + ps.setInt(2, detail.getMenuItemId()); + ps.setInt(3, detail.getQuantity()); + ps.setDouble(4, detail.getPrice()); // درست + + ps.executeUpdate(); + + } + catch (SQLException e) {System.out.println("Error saving order detail: " + e.getMessage());} } - public List findByOrderId(int orderId) { + public List findByOrderId(int orderId) + { + List details = new ArrayList<>(); - // TODO: - // Retrieve order details + String sql = """ + SELECT id, order_id, menu_item_id, quantity, price_at_purchase + FROM order_details + WHERE order_id = ? + """; - return null; + try (PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setInt(1, orderId); + + try (ResultSet rs = ps.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("Error fetching order details: " + e.getMessage());} + + 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..22dd33a 100644 --- a/src/main/java/dev/dao/UserDao.java +++ b/src/main/java/dev/dao/UserDao.java @@ -2,22 +2,69 @@ package dev.dao; import dev.model.User; -public class UserDao { +import java.sql.*; - public boolean save(User user) { +public class UserDao +{ + private final Connection connection; - // TODO: - // Insert user into database + public UserDao(Connection connection) {this.connection = connection;} - return false; + public boolean save(User user) + { + String sql = """ + INSERT INTO users (username, password, email) + VALUES (?, ?, ?) + """; + + try (PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setString(1, user.getUsername()); + ps.setString(2, user.getPassword()); + ps.setString(3, user.getEmail()); + + int rowsAffected = ps.executeUpdate(); + + return rowsAffected > 0; + + } + catch (SQLException e) + { + System.out.println("Error saving user: " + e.getMessage()); + return false; + } } - public User findByUsername(String username) { + public User findByUsername(String username) + { + String sql = """ + SELECT id, username, password, email + FROM users + WHERE username = ? + """; - // TODO: - // Find a user by username + try (PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setString(1, username); + + try (ResultSet rs = ps.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("Error finding user: " + e.getMessage());} return null; } - } \ 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..8b15496 100644 --- a/src/main/java/dev/database/DatabaseConnection.java +++ b/src/main/java/dev/database/DatabaseConnection.java @@ -1,27 +1,26 @@ package dev.database; import java.sql.Connection; +import java.sql.DriverManager; import java.sql.SQLException; -public class DatabaseConnection { +public class DatabaseConnection +{ + private static final String URL = + "jdbc:postgresql://localhost:5432/restaurant_db"; - private static final String URL = "jdbc:postgresql://localhost:5432/restaurant_db"; // DB Server + private static final String USER = "postgres"; - private static final String USER = "postgres"; // Your Username + private static final String PASSWORD = "Romina85"; - private static final String PASSWORD = "password"; // Your Password + private DatabaseConnection() {} - private DatabaseConnection() { + public static Connection getConnection() throws SQLException + { + try {Class.forName("org.postgresql.Driver");} + catch (ClassNotFoundException e) {throw new RuntimeException("PostgreSQL Driver not found!", e);} + + return DriverManager.getConnection(URL, USER, PASSWORD); } - - public static Connection getConnection() - throws SQLException { - - // TODO: - // Return a valid PostgreSQL connection - - return null; - } - } \ 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..3bc2b1b 100644 --- a/src/main/java/dev/model/MenuItem.java +++ b/src/main/java/dev/model/MenuItem.java @@ -1,15 +1,43 @@ package dev.model; -public class MenuItem { - +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;} + + @Override + public String toString() + { + return "MenuItem{" + + "id=" + id + + ", name='" + name + '\'' + + ", description='" + description + '\'' + + ", price=" + price + + ", 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..b51db0b 100644 --- a/src/main/java/dev/model/Order.java +++ b/src/main/java/dev/model/Order.java @@ -2,14 +2,26 @@ package dev.model; import java.time.LocalDateTime; -public class Order { - +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..113ac94 100644 --- a/src/main/java/dev/model/OrderDetail.java +++ b/src/main/java/dev/model/OrderDetail.java @@ -1,15 +1,30 @@ package dev.model; -public class OrderDetail { - +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..9dacfcc 100644 --- a/src/main/java/dev/model/User.java +++ b/src/main/java/dev/model/User.java @@ -1,13 +1,25 @@ package dev.model; -public class User { - +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..268e6b7 100644 --- a/src/main/java/dev/service/AuthService.java +++ b/src/main/java/dev/service/AuthService.java @@ -1,23 +1,53 @@ package dev.service; +import dev.dao.UserDao; import dev.model.User; -public class AuthService { +public class AuthService +{ + private final UserDao userDao; - public boolean register(String username, String password, String email) { + public AuthService(UserDao userDao) {this.userDao = userDao;} - // TODO: - // Validate and register user + public boolean register(String username, String password, String email) + { + if (username == null || username.isBlank()) return false; + if (password == null || password.length() < 4) return false; - return false; + if (userDao.findByUsername(username) != null) + { + System.out.println("Username already exists!"); + return false; + } + + User user = new User(); + user.setUsername(username); + + user.setPassword(password); + + user.setEmail(email); + + return userDao.save(user); } - public User login(String username, String password) { + public User login(String username, String password) + { + if (username == null || password == null) return null; - // TODO: - // Authenticate user + User user = userDao.findByUsername(username); - return null; + if (user == null) + { + System.out.println("User not found!"); + return null; + } + + if (!user.getPassword().equals(password)) + { + System.out.println("Wrong password!"); + return null; + } + + return user; } - } \ 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..ae89146 100644 --- a/src/main/java/dev/service/MenuService.java +++ b/src/main/java/dev/service/MenuService.java @@ -1,12 +1,41 @@ package dev.service; -public class MenuService { +import dev.dao.MenuItemDao; +import dev.model.MenuItem; - public void showMenu() { +import java.util.List; - // TODO: - // Display menu items +public class MenuService +{ + private final MenuItemDao menuItemDao; + public MenuService(MenuItemDao menuItemDao) {this.menuItemDao = menuItemDao;} + + public void showMenu() + { + List items = menuItemDao.findAll(); + + if (items == null || items.isEmpty()) + { + System.out.println("No menu items available."); + return; + } + + System.out.println("================================="); + System.out.println(" 🍽️ MENU"); + System.out.println("================================="); + + for (MenuItem item : items) + { + System.out.println( + item.getId() + ". " + + item.getName() + " - $" + + item.getPrice() + ); + + if (item.getDescription() != null) {System.out.println(" " + item.getDescription());} + } + + 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..be2fa87 100644 --- a/src/main/java/dev/service/OrderService.java +++ b/src/main/java/dev/service/OrderService.java @@ -1,26 +1,152 @@ package dev.service; -public class OrderService { +import dev.dao.MenuItemDao; +import dev.dao.OrderDao; +import dev.dao.OrderDetailDao; +import dev.model.MenuItem; +import dev.model.Order; +import dev.model.OrderDetail; - public void placeOrder(int userId) { +import java.time.LocalDateTime; +import java.util.List; +import java.util.Scanner; - // TODO: - // Create order +public class OrderService +{ + private final OrderDao orderDao; + private final OrderDetailDao orderDetailDao; + private final MenuItemDao menuItemDao; + public OrderService(OrderDao orderDao, + OrderDetailDao orderDetailDao, + MenuItemDao menuItemDao) { + this.orderDao = orderDao; + this.orderDetailDao = orderDetailDao; + this.menuItemDao = menuItemDao; } - public void printReceipt(int orderId) { + public void placeOrder(int userId) + { + Scanner scanner = new Scanner(System.in); - // TODO: - // Print order receipt + double totalPrice = 0; + Order order = new Order(); + order.setUserId(userId); + order.setCreatedAt(LocalDateTime.now()); + order.setTotalPrice(0); + + int orderId = orderDao.save(order); + + if (orderId == -1) + { + System.out.println("Failed to create order!"); + return; + } + + System.out.println("Available Menu:"); + List items = menuItemDao.findAll(); + + for (MenuItem item : items) + { + System.out.println(item.getId() + ". " + + item.getName() + " - $" + + item.getPrice()); + } + + while (true) + { + System.out.print("Enter item id (0 to finish): "); + int itemId = scanner.nextInt(); + + if (itemId == 0) break; + + MenuItem menuItem = menuItemDao.findById(itemId); + + if (menuItem == null) + { + System.out.println("Invalid item!"); + continue; + } + + System.out.print("Enter quantity: "); + int qty = scanner.nextInt(); + + double itemTotal = menuItem.getPrice() * qty; + totalPrice += itemTotal; + + OrderDetail detail = new OrderDetail(); + detail.setOrderId(orderId); + detail.setMenuItemId(itemId); + detail.setQuantity(qty); + detail.setPrice(menuItem.getPrice()); + + orderDetailDao.save(detail); + + System.out.println("Added: " + qty + " x " + menuItem.getName()); + } + + System.out.println("================================="); + System.out.println("Final Total: $" + totalPrice); + System.out.println("Order placed successfully!"); } - public void showOrderHistory(int userId) { + public void printReceipt(int orderId) + { + List details = orderDetailDao.findByOrderId(orderId); - // TODO: - // Display user's order history + if (details.isEmpty()) + { + System.out.println("No order found!"); + return; + } + System.out.println("================================="); + System.out.println(" RECEIPT"); + System.out.println("Order ID: " + orderId); + System.out.println("================================="); + System.out.println("Item\tQty\tPrice\tTotal"); + + double grandTotal = 0; + + for (OrderDetail d : details) + { + MenuItem item = menuItemDao.findById(d.getMenuItemId()); + + double total = d.getQuantity() * d.getPrice(); + grandTotal += total; + + System.out.println(item.getName() + "\t" + + d.getQuantity() + "\t" + + d.getPrice() + "\t" + + total); + } + + System.out.println("================================="); + System.out.println("Grand Total: $" + grandTotal); + System.out.println("================================="); } + public void showOrderHistory(int userId) + { + List orders = orderDao.findByUserId(userId); + + if (orders.isEmpty()) + { + System.out.println("No orders found."); + return; + } + + System.out.println("================================="); + System.out.println(" ORDER HISTORY"); + System.out.println("================================="); + + for (Order order : orders) + { + System.out.println("Order ID: " + order.getId()); + System.out.println("Date: " + order.getCreatedAt()); + System.out.println("Total: $" + order.getTotalPrice()); + System.out.println("---------------------------------"); + } + } } \ 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..80775f0 100644 --- a/src/main/java/dev/ui/ConsoleMenu.java +++ b/src/main/java/dev/ui/ConsoleMenu.java @@ -1,16 +1,34 @@ package dev.ui; +import dev.model.User; +import dev.service.AuthService; +import dev.service.MenuService; +import dev.service.OrderService; + import java.util.Scanner; -public class ConsoleMenu { +public class ConsoleMenu +{ + private final Scanner scanner = new Scanner(System.in); - private final Scanner scanner = - new Scanner(System.in); + private final AuthService authService; + private final MenuService menuService; + private final OrderService orderService; - public void start() { + private User loggedInUser; - while (true) { + public ConsoleMenu(AuthService authService, + MenuService menuService, + OrderService orderService) { + this.authService = authService; + this.menuService = menuService; + this.orderService = orderService; + } + public void start() + { + while (true) + { System.out.println(); System.out.println("===== JAVA PIZZERIA ====="); System.out.println("1. Login"); @@ -18,27 +36,91 @@ public class ConsoleMenu { System.out.println("3. Exit"); int choice = scanner.nextInt(); + scanner.nextLine(); - switch (choice) { + switch (choice) + { + case 1 -> login(); - case 1: - // TODO - break; + case 2 -> register(); - case 2: - // TODO - break; - - case 3: + case 3 -> + { + System.out.println("Goodbye!"); return; + } - default: - System.out.println("Invalid choice"); - + default -> System.out.println("Invalid choice"); } - } - } + private void login() + { + System.out.print("Username: "); + String username = scanner.nextLine(); + + System.out.print("Password: "); + String password = scanner.nextLine(); + + User user = authService.login(username, password); + + if (user != null) + { + loggedInUser = user; + System.out.println("Login successful!"); + userMenu(); + } + else {System.out.println("Login failed!");} + } + + private void register() + { + System.out.print("Username: "); + String username = scanner.nextLine(); + + System.out.print("Password: "); + String password = scanner.nextLine(); + + System.out.print("Email: "); + String email = scanner.nextLine(); + + boolean success = authService.register(username, password, email); + + if (success) {System.out.println("Registration successful!");} + else {System.out.println("Registration failed!");} + } + + private void userMenu() + { + while (true) + { + System.out.println(); + System.out.println("===== MAIN MENU ====="); + System.out.println("1. View Menu"); + System.out.println("2. Place Order"); + System.out.println("3. Order History"); + System.out.println("4. Logout"); + + int choice = scanner.nextInt(); + scanner.nextLine(); + + switch (choice) + { + case 1 -> menuService.showMenu(); + + case 2 -> orderService.placeOrder(loggedInUser.getId()); + + case 3 -> orderService.showOrderHistory(loggedInUser.getId()); + + case 4 -> + { + loggedInUser = null; + return; + } + + default -> System.out.println("Invalid choice"); + } + } + } } \ No newline at end of file