diff --git a/database.sql b/database.sql index 2169346..3ebe4ae 100644 --- a/database.sql +++ b/database.sql @@ -1,141 +1,62 @@ --- 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. +CREATE DATABASE restaurant_db; +DROP TABLE IF EXISTS order_details; +DROP TABLE IF EXISTS orders; +DROP TABLE IF EXISTS menu_items; +DROP TABLE IF EXISTS users; --- ======================================================= --- 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(64) NOT NULL, + email VARCHAR(100) +); +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) +); +CREATE TABLE orders +( + id SERIAL PRIMARY KEY, + user_id INTEGER NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + total_price NUMERIC(10,2) NOT NULL CHECK(total_price >= 0), --- ======================================================= --- 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 ... + CONSTRAINT fk_orders_user + FOREIGN KEY(user_id) + REFERENCES users(id) + ON DELETE CASCADE +); +CREATE TABLE order_details +( + id SERIAL PRIMARY KEY, + order_id INTEGER NOT NULL, + menu_item_id INTEGER NOT NULL, + quantity INTEGER NOT NULL CHECK(quantity > 0), + price NUMERIC(10,2) NOT NULL CHECK(price > 0), + CONSTRAINT fk_detail_order + FOREIGN KEY(order_id) + REFERENCES orders(id) + ON DELETE CASCADE, --- ======================================================= --- 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 ... + CONSTRAINT fk_detail_menu + FOREIGN KEY(menu_item_id) + REFERENCES menu_items(id) +); - - --- ======================================================= --- 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 ... - - - --- ======================================================= --- INITIAL MENU DATA --- ======================================================= --- --- Insert at least 3 food or drink items. --- --- Example categories: --- - Pizza --- - Burger --- - Pasta --- - Drink --- --- INSERT INTO ... - - - --- ======================================================= --- 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 +INSERT INTO menu_items(name,description,price,category) +VALUES + ('Pizza Margherita','Classic pizza',10.00,'Pizza'), + ('Cheese Burger','Beef burger',8.00,'Burger'), + ('Chicken Pasta','Creamy pasta',12.00,'Pasta'), + ('Cola','Cold drink',2.50,'Drink'); \ No newline at end of file diff --git a/src/main/java/dev/Main.java b/src/main/java/dev/Main.java index 3a93683..27b18fe 100644 --- a/src/main/java/dev/Main.java +++ b/src/main/java/dev/Main.java @@ -8,7 +8,5 @@ public class Main { ConsoleMenu menu = new ConsoleMenu(); menu.start(); - } - } \ 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..cc55e41 100644 --- a/src/main/java/dev/dao/MenuItemDao.java +++ b/src/main/java/dev/dao/MenuItemDao.java @@ -1,25 +1,76 @@ package dev.dao; +import dev.database.DatabaseConnection; import dev.model.MenuItem; +import java.sql.*; +import java.util.ArrayList; import java.util.List; -public class MenuItemDao { +public class MenuItemDao +{ + public List findAll() + { + List items = new ArrayList<>(); - public List findAll() { + String sql = "SELECT * FROM menu_items"; - // TODO: - // Retrieve all menu items + try(Connection connection = DatabaseConnection.getConnection(); + 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) + { + e.printStackTrace(); + } + + return items; + } + + public MenuItem findById(int id) + { + String sql = "SELECT * FROM menu_items WHERE id=?"; + + try(Connection connection = DatabaseConnection.getConnection(); + PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setInt(1,id); + + 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) + { + e.printStackTrace(); + } 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..3ca5b43 100644 --- a/src/main/java/dev/dao/OrderDao.java +++ b/src/main/java/dev/dao/OrderDao.java @@ -1,25 +1,85 @@ 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.Statement; +import java.sql.Timestamp; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; -public class OrderDao { +public class OrderDao +{ + public int save(Order order) + { + String sql = + """ + INSERT INTO orders + (user_id, created_at, total_price) + VALUES (?, ?, ?) + """; - public int save(Order order) { + try (Connection connection = DatabaseConnection.getConnection(); + 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()); + ps.executeUpdate(); - // TODO: - // Insert order and return generated id + ResultSet rs = ps.getGeneratedKeys(); + + if (rs.next()) + return rs.getInt(1); + + } + catch (SQLException e) + { + e.printStackTrace(); + } 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 * + FROM orders + WHERE user_id = ? + ORDER BY created_at DESC + """; - return null; + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setInt(1, userId); + 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) + { + e.printStackTrace(); + } + + 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..477c7c4 100644 --- a/src/main/java/dev/dao/OrderDetailDao.java +++ b/src/main/java/dev/dao/OrderDetailDao.java @@ -1,24 +1,77 @@ 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 class OrderDetailDao +{ + public void save(OrderDetail detail) + { + String sql = + """ + INSERT INTO order_details + (order_id, menu_item_id, quantity, price) + VALUES (?, ?, ?, ?) + """; - public void save(OrderDetail detail) { - - // TODO: - // Insert order detail + try (Connection connection = DatabaseConnection.getConnection(); + 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) + { + e.printStackTrace(); + } } - public List findByOrderId(int orderId) { + public List findByOrderId(int orderId) + { + List details = new ArrayList<>(); - // TODO: - // Retrieve order details + String sql = + """ + SELECT * + FROM order_details + WHERE order_id = ? + """; - return null; + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setInt(1, orderId); + 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")); + + details.add(detail); + } + + } + catch (SQLException e) + { + e.printStackTrace(); + } + + 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..fc2d3f2 100644 --- a/src/main/java/dev/dao/UserDao.java +++ b/src/main/java/dev/dao/UserDao.java @@ -1,23 +1,60 @@ package dev.dao; +import dev.database.DatabaseConnection; import dev.model.User; +import java.sql.*; -public class UserDao { +public class UserDao +{ + public boolean save(User user) + { + String sql = "INSERT INTO users(username,password,email) VALUES(?,?,?)"; - public boolean save(User user) { + try(Connection connection = DatabaseConnection.getConnection(); + PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setString(1,user.getUsername()); + ps.setString(2,user.getPassword()); + ps.setString(3,user.getEmail()); - // TODO: - // Insert user into database - - return false; + return ps.executeUpdate() > 0; + } + catch (SQLException e) + { + e.printStackTrace(); + return false; + } } - public User findByUsername(String username) { + public User findByUsername(String username) + { + String sql = "SELECT * FROM users WHERE username=?"; - // TODO: - // Find a user by username + try(Connection connection = DatabaseConnection.getConnection(); + PreparedStatement ps = connection.prepareStatement(sql)) + { + ps.setString(1,username); + + 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) + { + e.printStackTrace(); + } 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..0ed536a 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 { @@ -9,19 +10,13 @@ public class DatabaseConnection { private static final String USER = "postgres"; // Your Username - private static final String PASSWORD = "password"; // Your Password + private static final String PASSWORD = "99242096"; // Your Password - private DatabaseConnection() { + private 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/CartItem.java b/src/main/java/dev/model/CartItem.java new file mode 100644 index 0000000..38c72d4 --- /dev/null +++ b/src/main/java/dev/model/CartItem.java @@ -0,0 +1,34 @@ +package dev.model; + +public class CartItem { + + private MenuItem menuItem; + + private int quantity; + + public CartItem(MenuItem menuItem, int quantity) + { + this.menuItem = menuItem; + this.quantity = quantity; + } + + public MenuItem getMenuItem() + { + return menuItem; + } + + public void setMenuItem(MenuItem menuItem) + { + this.menuItem = menuItem; + } + + public int getQuantity() + { + return quantity; + } + + public void setQuantity(int quantity) + { + this.quantity = quantity; + } +} \ 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..5b9400c 100644 --- a/src/main/java/dev/model/MenuItem.java +++ b/src/main/java/dev/model/MenuItem.java @@ -12,4 +12,75 @@ public class MenuItem { private String category; + public MenuItem() { + } + + public MenuItem(int id, + String name, + String description, + double price, + String category) { + + this.id = id; + this.name = name; + this.description = description; + this.price = price; + this.category = 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 id + " - " + name + " ($" + price + ")"; + } } \ 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..e58d7c8 100644 --- a/src/main/java/dev/model/Order.java +++ b/src/main/java/dev/model/Order.java @@ -12,4 +12,68 @@ public class Order { private double totalPrice; + public Order() { + } + + public Order(int id, + int userId, + LocalDateTime createdAt, + double totalPrice) { + + this.id = id; + this.userId = userId; + this.createdAt = createdAt; + this.totalPrice = 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; + } + + @Override + public String toString() + { + return "Order{" + + "id=" + id + + ", userId=" + userId + + ", createdAt=" + createdAt + + ", 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..218480c 100644 --- a/src/main/java/dev/model/OrderDetail.java +++ b/src/main/java/dev/model/OrderDetail.java @@ -12,4 +12,80 @@ public class OrderDetail { private double price; + public OrderDetail() { + } + + public OrderDetail(int id, + int orderId, + int menuItemId, + int quantity, + double price) { + + this.id = id; + this.orderId = orderId; + this.menuItemId = menuItemId; + this.quantity = quantity; + this.price = 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; + } + + @Override + public String toString() + { + return "OrderDetail{" + + "id=" + id + + ", orderId=" + orderId + + ", menuItemId=" + menuItemId + + ", quantity=" + quantity + + ", 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..144224f 100644 --- a/src/main/java/dev/model/User.java +++ b/src/main/java/dev/model/User.java @@ -10,4 +10,66 @@ public class User { private String email; + public User() {} + + public User(int id, + String username, + String password, + String email) + { + this.id = id; + this.username = username; + this.password = password; + this.email = 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; + } + + @Override + public String toString() + { + return "User{" + + "id=" + id + + ", username='" + username + '\'' + + ", 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..50e0a84 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; +import dev.util.PasswordUtil; -public class AuthService { +public class AuthService +{ + private final UserDao userDao = new UserDao(); - public boolean register(String username, String password, String email) { + public boolean register( + String username, + String password, + String email) + { + User existingUser = userDao.findByUsername(username); - // TODO: - // Validate and register user + if (existingUser != null) + { + System.out.println("Username already exists."); + return false; + } - return false; + User user = new User(); + user.setUsername(username); + user.setPassword(PasswordUtil.hash(password)); + user.setEmail(email); + + return userDao.save(user); } - public User login(String username, String password) { + public User login( + String username, + String password) + { - // TODO: - // Authenticate user + User user = userDao.findByUsername(username); - return null; + if (user == null) + { + System.out.println("Invalid username."); + return null; + } + + if (!PasswordUtil.matches(password, user.getPassword())) + { + System.out.println("Invalid 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..2bb515e 100644 --- a/src/main/java/dev/service/MenuService.java +++ b/src/main/java/dev/service/MenuService.java @@ -1,12 +1,31 @@ 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 = new MenuItemDao(); + public void showMenu() + { + List items = menuItemDao.findAll(); + + System.out.println(); + System.out.println("========== MENU =========="); + + for (MenuItem item : items) + { + System.out.printf( + "%d - %s - $%.2f%n", + item.getId(), + item.getName(), + 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..1a83aab 100644 --- a/src/main/java/dev/service/OrderService.java +++ b/src/main/java/dev/service/OrderService.java @@ -1,26 +1,178 @@ package dev.service; +import dev.dao.MenuItemDao; +import dev.dao.OrderDao; +import dev.dao.OrderDetailDao; +import dev.model.CartItem; +import dev.model.MenuItem; +import dev.model.Order; +import dev.model.OrderDetail; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + public class OrderService { - public void placeOrder(int userId) { + private final Scanner scanner = + new Scanner(System.in); - // TODO: - // Create order + private final MenuItemDao menuItemDao = + new MenuItemDao(); + private final OrderDao orderDao = + new OrderDao(); + + private final OrderDetailDao orderDetailDao = + new OrderDetailDao(); + + public void placeOrder(int userId) + { + List cart = new ArrayList<>(); + + while (true) + { + System.out.println(); + System.out.println("Available Items:"); + + List items = menuItemDao.findAll(); + + for (MenuItem item : items) + { + System.out.printf( + "%d - %s - $%.2f%n", + item.getId(), + item.getName(), + item.getPrice() + ); + } + + 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 id."); + continue; + } + + System.out.print("Quantity: "); + + int quantity = scanner.nextInt(); + + if (quantity <= 0) + { + System.out.println("Quantity must be positive."); + continue; + } + + cart.add(new CartItem(menuItem, quantity)); + + System.out.println("Added successfully."); + } + + if (cart.isEmpty()) + { + System.out.println("No items selected."); + return; + } + + double total = 0.0; + + for (CartItem cartItem : cart) + total += cartItem.getMenuItem().getPrice() * cartItem.getQuantity(); + + Order order = new Order(); + + order.setUserId(userId); + order.setCreatedAt(LocalDateTime.now()); + order.setTotalPrice(total); + + int orderId = orderDao.save(order); + + if (orderId == -1) + { + System.out.println("Failed to save order."); + return; + } + + for (CartItem cartItem : cart) + { + OrderDetail detail = new OrderDetail(); + detail.setOrderId(orderId); + detail.setMenuItemId(cartItem.getMenuItem().getId()); + detail.setQuantity(cartItem.getQuantity()); + detail.setPrice(cartItem.getMenuItem().getPrice()); + + orderDetailDao.save(detail); + } + + System.out.println(); + System.out.println("Order saved successfully."); + + printReceipt(orderId); } - public void printReceipt(int orderId) { + public void printReceipt(int orderId) + { + List details = orderDetailDao.findByOrderId(orderId); - // TODO: - // Print order receipt + System.out.println(); + System.out.println("========== RECEIPT =========="); + System.out.printf("%-15s %-8s %-10s %-10s%n", "Item", "Qty", "Unit", "Total"); + System.out.println("------------------------------------------"); + double grandTotal = 0; + + for (OrderDetail detail : details) + { + MenuItem item = menuItemDao.findById(detail.getMenuItemId()); + double subtotal = detail.getQuantity() * detail.getPrice(); + + grandTotal += subtotal; + + System.out.printf( + "%-15s %-8d %-10.2f %-10.2f%n", + item.getName(), + detail.getQuantity(), + detail.getPrice(), + subtotal + ); + } + + System.out.println("------------------------------------------"); + System.out.printf("Final Total: %.2f%n", grandTotal); + System.out.println("=============================="); } - public void showOrderHistory(int userId) { + public void showOrderHistory(int userId) + { + List orders = orderDao.findByUserId(userId); - // TODO: - // Display user's order history + if (orders.isEmpty()) + { + System.out.println("No orders found."); + return; + } + System.out.println(); + System.out.println("====== ORDER HISTORY ======"); + + for (Order order : orders) + { + System.out.printf( + "Order #%d | %s | $%.2f%n", + order.getId(), + order.getCreatedAt(), + order.getTotalPrice() + ); + } } - } \ 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..58562c1 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.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); - public void start() { + private final AuthService authService = + new AuthService(); - while (true) { + private final MenuService menuService = + new MenuService(); + private final OrderService orderService = + new OrderService(); + + public void start() + { + while (true) + { System.out.println(); - System.out.println("===== JAVA PIZZERIA ====="); + System.out.println("===================================="); + System.out.println(" JAVA PIZZERIA "); + System.out.println("===================================="); + System.out.println("1. Login"); System.out.println("2. Register"); System.out.println("3. Exit"); + System.out.print("Choose option: "); + int choice = scanner.nextInt(); - switch (choice) { + scanner.nextLine(); - case 1: - // TODO - break; + switch (choice) + { + case 1 -> login(); - case 2: - // TODO - break; + case 2 -> register(); - case 3: + case 3 -> + { + System.out.println("Goodbye."); return; + } - default: - System.out.println("Invalid choice"); - + default -> System.out.println("Invalid choice."); } - } - } + private void register() + { + System.out.println(); + System.out.println("===== 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 login() + { + System.out.println(); + System.out.println("===== 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) + { + System.out.println("Login failed."); + return; + } + + System.out.println("Welcome " + user.getUsername()); + showUserMenu(user); + } + + private void showUserMenu(User user) + { + 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. View Order History"); + System.out.println("4. Logout"); + + System.out.print("Choose option: "); + + int choice = scanner.nextInt(); + + switch (choice) + { + case 1 -> menuService.showMenu(); + + case 2 -> orderService.placeOrder(user.getId()); + + case 3 -> orderService.showOrderHistory(user.getId()); + + case 4 -> + { + return; + } + + default -> System.out.println("Invalid choice."); + } + } + } } \ No newline at end of file diff --git a/src/main/java/dev/util/PasswordUtil.java b/src/main/java/dev/util/PasswordUtil.java new file mode 100644 index 0000000..c3faf5c --- /dev/null +++ b/src/main/java/dev/util/PasswordUtil.java @@ -0,0 +1,34 @@ +package dev.util; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; + +public class PasswordUtil +{ + private PasswordUtil() {} + + public static String hash(String password) + { + try + { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + byte[] hash = md.digest(password.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + + for (byte b : hash) + sb.append(String.format("%02x", b)); + + return sb.toString(); + + } + catch (Exception e) + { + throw new RuntimeException(e); + } + } + + public static boolean matches(String rawPassword, String hashedPassword) + { + return hash(rawPassword).equals(hashedPassword); + } +} \ No newline at end of file