From 0841d7e8464df0f0be8f1411d123247379bfc97e Mon Sep 17 00:00:00 2001 From: SaraZoveydavian Date: Thu, 25 Jun 2026 20:56:19 +0330 Subject: [PATCH 1/2] database script completed --- database.sql | 190 ++++++++++++++++++--------------------------------- 1 file changed, 66 insertions(+), 124 deletions(-) diff --git a/database.sql b/database.sql index 2169346..bac0ec9 100644 --- a/database.sql +++ b/database.sql @@ -1,141 +1,83 @@ --- 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_item 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 ( + uid 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_item ( + uid SERIAL PRIMARY KEY, + name VARCHAR(50) NOT NULL, + price DECIMAL(10, 2) NOT NULL CHECK (price > 0), + category VARCHAR(50) +); +CREATE TABLE orders ( + uid SERIAL PRIMARY KEY, + user_id INTEGER NOT NULL, + order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + total_price DECIMAL(10, 2) NOT NULL CHECK (total_price >= 0), --- ======================================================= --- 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_orders_user + FOREIGN KEY (user_id) + REFERENCES users(uid) + ON DELETE CASCADE +); +CREATE TABLE order_details ( + uid SERIAL PRIMARY KEY, + order_id INTEGER NOT NULL, + item_id INTEGER NOT NULL, + quantity INTEGER NOT NULL CHECK (quantity > 0), + item_price DECIMAL(10, 2) NOT NULL CHECK (item_price >= 0), --- ======================================================= --- 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 ... + CONSTRAINT fk_order_details_order + FOREIGN KEY (order_id) + REFERENCES orders(uid) + ON DELETE CASCADE, + + CONSTRAINT fk_order_details_menu_item + FOREIGN KEY (item_id) + REFERENCES menu_item(uid) + ON DELETE RESTRICT +); - --- ======================================================= --- INITIAL MENU DATA --- ======================================================= --- --- Insert at least 3 food or drink items. --- --- Example categories: --- - Pizza --- - Burger --- - Pasta --- - Drink --- --- INSERT INTO ... +INSERT INTO menu_item (name, price, category) VALUES + ('French Fries', 1.00, 'Appetizer'), + ('Chicken Burger', 4.05, 'Burger'), + ('Pepperoni Pizza', 8.39, 'Pizza'), + ('Milkshake', 2.20, 'Drink'), + ('Ravioli', 9.00, 'Pasta'); - --- ======================================================= --- OPTIONAL TEST DATA --- ======================================================= --- --- You may insert sample users and orders for testing. --- This section is optional. --- --- INSERT INTO ... +INSERT INTO users (username, password, email) VALUES + ('saraz', '8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92', 'sarrr@gmail.com'), + ('kave02', '8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92', 'kaviii02@gmail.com'), + ('titami_t', '8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92', 'titaza@gmil.com'); +INSERT INTO orders (user_id, order_date, total_price) VALUES + (1, CURRENT_TIMESTAMP, 9.39), + (2, CURRENT_TIMESTAMP, 13.05), + (1, CURRENT_TIMESTAMP, 2.20), + (3, CURRENT_TIMESTAMP, 8.39); --- ======================================================= --- 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 order_details (order_id, item_id, quantity, item_price) VALUES + (1, 1, 1, 1.00), + (1, 3, 1, 8.39), + (2, 2, 1, 4.05), + (2, 5, 1, 9.00), + (3, 4, 1, 2.20), + (4, 3, 1, 8.39); \ No newline at end of file -- 2.54.0 From acf5c9bb43a3e3b92385b58d5a8d206b54d2363e Mon Sep 17 00:00:00 2001 From: SaraZoveydavian Date: Thu, 25 Jun 2026 21:00:15 +0330 Subject: [PATCH 2/2] all required classes copmleted --- .idea/.gitignore | 10 + .idea/compiler.xml | 13 ++ .idea/dataSources.xml | 17 ++ .idea/encodings.xml | 7 + .idea/inspectionProfiles/Project_Default.xml | 6 + .idea/jarRepositories.xml | 20 ++ .idea/misc.xml | 12 ++ .idea/sqldialects.xml | 6 + .idea/vcs.xml | 6 + src/main/java/dev/dao/MenuItemDao.java | 52 ++++- src/main/java/dev/dao/OrderDao.java | 74 ++++++- src/main/java/dev/dao/OrderDetailDao.java | 53 ++++- src/main/java/dev/dao/UserDao.java | 45 ++++- .../java/dev/database/DatabaseConnection.java | 28 ++- src/main/java/dev/model/MenuItem.java | 36 +++- src/main/java/dev/model/Order.java | 38 +++- src/main/java/dev/model/OrderDetail.java | 52 ++++- src/main/java/dev/model/User.java | 34 +++- src/main/java/dev/service/AuthService.java | 93 ++++++++- src/main/java/dev/service/MenuService.java | 48 ++++- src/main/java/dev/service/OrderService.java | 190 +++++++++++++++++- src/main/java/dev/ui/ConsoleMenu.java | 154 ++++++++++---- 22 files changed, 887 insertions(+), 107 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/compiler.xml create mode 100644 .idea/dataSources.xml create mode 100644 .idea/encodings.xml create mode 100644 .idea/inspectionProfiles/Project_Default.xml create mode 100644 .idea/jarRepositories.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/sqldialects.xml create mode 100644 .idea/vcs.xml 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/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 0000000..573a5d1 --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,17 @@ + + + + + postgresql + true + org.postgresql.Driver + jdbc:postgresql://localhost:5432/postgres + + + + + + $ProjectFileDir$ + + + \ 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/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..5cb71ef --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..a9076af --- /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..652d615 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/sqldialects.xml b/.idea/sqldialects.xml new file mode 100644 index 0000000..1df8135 --- /dev/null +++ b/.idea/sqldialects.xml @@ -0,0 +1,6 @@ + + + + + + \ 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/src/main/java/dev/dao/MenuItemDao.java b/src/main/java/dev/dao/MenuItemDao.java index 3bbebe9..dbf6638 100644 --- a/src/main/java/dev/dao/MenuItemDao.java +++ b/src/main/java/dev/dao/MenuItemDao.java @@ -1,25 +1,65 @@ 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() { + String query = "SELECT uid, name, price, category FROM menu_item ORDER BY uid"; + List items = new ArrayList<>(); - // TODO: - // Retrieve all menu items + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement ps = conn.prepareStatement(query)) { - return null; + ResultSet rs = ps.executeQuery(); + + while (rs.next()) { + MenuItem item = new MenuItem(); + item.setId(rs.getInt("uid")); + item.setName(rs.getString("name")); + item.setPrice(rs.getDouble("price")); + item.setCategory(rs.getString("category")); + items.add(item); + } + + return items; + + } catch (SQLException e) { + System.err.println("Error finding menu items: " + e.getMessage()); + return new ArrayList<>(); + } } public MenuItem findById(int id) { + String query = "SELECT uid, name, price, category FROM menu_item WHERE uid = ?"; - // TODO: - // Find menu item by id + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement ps = conn.prepareStatement(query)) { + + ps.setInt(1, id); + ResultSet rs = ps.executeQuery(); + + if (rs.next()) { + MenuItem item = new MenuItem(); + item.setId(rs.getInt("uid")); + item.setName(rs.getString("name")); + item.setPrice(rs.getDouble("price")); + item.setCategory(rs.getString("category")); + return item; + } + + } catch (SQLException e) { + System.err.println("Error finding menu item by ID: " + e.getMessage()); + } 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..6fa7b72 100644 --- a/src/main/java/dev/dao/OrderDao.java +++ b/src/main/java/dev/dao/OrderDao.java @@ -1,25 +1,89 @@ package dev.dao; +import dev.database.DatabaseConnection; import dev.model.Order; +import java.sql.*; +import java.util.ArrayList; import java.util.List; public class OrderDao { public int save(Order order) { + String query = "INSERT INTO orders (user_id, order_date, total_price) VALUES (?, ?, ?)"; - // TODO: - // Insert order and return generated id + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement ps = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { + + ps.setInt(1, order.getUserId()); + ps.setTimestamp(2, order.getCreatedAt()); + ps.setDouble(3, order.getTotalPrice()); + + int rowsAffected = ps.executeUpdate(); + + if (rowsAffected == 1) { + ResultSet rs = ps.getGeneratedKeys(); + if (rs.next()) { + return rs.getInt(1); + } + } + + } catch (SQLException e) { + System.err.println("Error saving order: " + e.getMessage()); + } return -1; } public List findByUserId(int userId) { + String query = "SELECT uid, user_id, order_date, total_price FROM orders WHERE user_id = ?"; + List orders = new ArrayList<>(); - // TODO: - // Retrieve all orders of a user + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement ps = conn.prepareStatement(query)) { + + ps.setInt(1, userId); + ResultSet rs = ps.executeQuery(); + + while (rs.next()) { + Order order = new Order(); + order.setId(rs.getInt("uid")); + order.setUserId(rs.getInt("user_id")); + order.setCreatedAt(rs.getTimestamp("order_date")); + order.setTotalPrice(rs.getDouble("total_price")); + orders.add(order); + } + + return orders; + + } catch (SQLException e) { + System.err.println("Error finding orders: " + e.getMessage()); + return new ArrayList<>(); + } + } + + public Order findById(int orderId) { + String query = "SELECT uid, user_id, order_date, total_price FROM orders WHERE uid = ?"; + + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement ps = conn.prepareStatement(query)) { + + ps.setInt(1, orderId); + ResultSet rs = ps.executeQuery(); + + if (rs.next()) { + Order order = new Order(); + order.setId(rs.getInt("uid")); + order.setUserId(rs.getInt("user_id")); + order.setCreatedAt(rs.getTimestamp("order_date")); + order.setTotalPrice(rs.getDouble("total_price")); + return order; + } + + } catch (SQLException e) { + System.err.println("Error finding order by ID: " + e.getMessage()); + } return null; } - } \ 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..ff098eb 100644 --- a/src/main/java/dev/dao/OrderDetailDao.java +++ b/src/main/java/dev/dao/OrderDetailDao.java @@ -1,24 +1,65 @@ 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 query = "INSERT INTO orders_detail (order_id, item_id, quantity, item_price) VALUES (?, ?, ?, ?)"; - // TODO: - // Insert order detail + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement ps = conn.prepareStatement(query)) { + 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.err.println("Error saving order detail: " + e.getMessage()); + } } public List findByOrderId(int orderId) { + String query = "SELECT od.uid, od.order_id, od.item_id, od.quantity, od.item_price, mi.name AS item_name " + + "FROM orders_detail od " + + "JOIN menu_item mi ON od.item_id = mi.uid " + + "WHERE od.order_id = ? " + + "ORDER BY od.uid"; - // TODO: - // Retrieve order details + List details = new ArrayList<>(); - return null; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement ps = conn.prepareStatement(query)) { + + ps.setInt(1, orderId); + ResultSet rs = ps.executeQuery(); + + while (rs.next()) { + OrderDetail detail = new OrderDetail(); + detail.setId(rs.getInt("uid")); + detail.setOrderId(rs.getInt("order_id")); + detail.setMenuItemId(rs.getInt("item_id")); + detail.setQuantity(rs.getInt("quantity")); + detail.setPrice(rs.getDouble("item_price")); + details.add(detail); + } + + return details; + + } catch (SQLException e) { + System.err.println("Error finding order details: " + e.getMessage()); + return new ArrayList<>(); + } } - } \ 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..bd4f57a 100644 --- a/src/main/java/dev/dao/UserDao.java +++ b/src/main/java/dev/dao/UserDao.java @@ -1,23 +1,56 @@ 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 query = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)"; - // TODO: - // Insert user into database + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement ps = conn.prepareStatement(query)) { - return false; + ps.setString(1, user.getUsername()); + ps.setString(2, user.getPassword()); + ps.setString(3, user.getEmail()); + + int rowsAffected = ps.executeUpdate(); + return rowsAffected == 1; + + } catch (SQLException e) { + System.err.println("Error saving user: " + e.getMessage()); + return false; + } } public User findByUsername(String username) { + String query = "SELECT uid, username, password, email FROM users WHERE username = ?"; - // TODO: - // Find a user by username + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement ps = conn.prepareStatement(query)) { + + ps.setString(1, username); + ResultSet rs = ps.executeQuery(); + + if (rs.next()) { + User user = new User(); + user.setId(rs.getInt("uid")); + user.setUsername(rs.getString("username")); + user.setPassword(rs.getString("password")); + user.setEmail(rs.getString("email")); + return user; + } + + } catch (SQLException e) { + System.err.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..5e1f3d7 100644 --- a/src/main/java/dev/database/DatabaseConnection.java +++ b/src/main/java/dev/database/DatabaseConnection.java @@ -1,27 +1,23 @@ package dev.database; import java.sql.Connection; +import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseConnection { - private static final String URL = "jdbc:postgresql://localhost:5432/restaurant_db"; // DB Server + private static final String URL = "jdbc:postgresql://localhost:5432/restaurant_db"; + private static final String USER = "postgres"; + private static final String PASSWORD = "1381sa"; - private static final String USER = "postgres"; // Your Username - - private static final String PASSWORD = "password"; // Your Password - - private DatabaseConnection() { + private DatabaseConnection() {} + public static Connection getConnection() throws SQLException { + try { + Class.forName("org.postgresql.Driver"); + return DriverManager.getConnection(URL, USER, PASSWORD); + } catch (ClassNotFoundException e) { + throw new SQLException("PostgreSQL Driver not found!", e); + } } - - 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..afb5f95 100644 --- a/src/main/java/dev/model/MenuItem.java +++ b/src/main/java/dev/model/MenuItem.java @@ -3,13 +3,39 @@ 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 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..f6d0f25 100644 --- a/src/main/java/dev/model/Order.java +++ b/src/main/java/dev/model/Order.java @@ -1,15 +1,43 @@ package dev.model; -import java.time.LocalDateTime; +import java.sql.Timestamp; public class Order { private int id; - private int userId; - - private LocalDateTime createdAt; - + private Timestamp 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 Timestamp getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Timestamp 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..1ee8dd9 100644 --- a/src/main/java/dev/model/OrderDetail.java +++ b/src/main/java/dev/model/OrderDetail.java @@ -3,13 +3,57 @@ package dev.model; public class OrderDetail { private int id; - private int orderId; - private int menuItemId; - private int quantity; - private double price; + private String itemName; + 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; + } + + public String getItemName() { + return itemName; + } + + public void setItemName(String itemName) { + this.itemName = itemName; + } } \ 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..92a396e 100644 --- a/src/main/java/dev/model/User.java +++ b/src/main/java/dev/model/User.java @@ -3,11 +3,39 @@ 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..8d61436 100644 --- a/src/main/java/dev/service/AuthService.java +++ b/src/main/java/dev/service/AuthService.java @@ -1,23 +1,104 @@ package dev.service; +import dev.dao.UserDao; import dev.model.User; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + public class AuthService { public boolean register(String username, String password, String email) { + if (username == null || username.trim().isEmpty()) { + System.out.println("Username cannot be empty"); + return false; + } + if (password == null || password.trim().isEmpty()) { + System.out.println("Password cannot be empty"); + return false; + } - // TODO: - // Validate and register user + try { + UserDao userDao = new UserDao(); - return false; + User existingUser = userDao.findByUsername(username); + if (existingUser != null) { + System.out.println("Username '" + username + "' is already taken!"); + return false; + } + + String hashedPassword = hashPassword(password); + + User user = new User(); + user.setUsername(username); + user.setPassword(hashedPassword); + user.setEmail(email); + + boolean saved = userDao.save(user); + + if (saved) { + System.out.println("Registration successful! Welcome " + username + "!"); + } else { + System.out.println("Registration failed. Please try again."); + } + + return saved; + + } catch (Exception e) { + System.err.println("Registration error: " + e.getMessage()); + return false; + } } public User login(String username, String password) { + if (username == null || username.trim().isEmpty()) { + System.out.println("Username cannot be empty"); + return null; + } + if (password == null || password.trim().isEmpty()) { + System.out.println("Password cannot be empty"); + return null; + } - // TODO: - // Authenticate user + try { + UserDao userDao = new UserDao(); - return null; + User user = userDao.findByUsername(username); + + if (user == null) { + System.out.println("User '" + username + "' not found!"); + return null; + } + + String hashedEnteredPassword = hashPassword(password); + + if (hashedEnteredPassword.equals(user.getPassword())) { + System.out.println("Login successful! Welcome back " + username + "!"); + return user; + } else { + System.out.println("Invalid password!"); + return null; + } + + } catch (Exception e) { + System.err.println("Login error: " + e.getMessage()); + return null; + } } + private String hashPassword(String password) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + byte[] hashBytes = md.digest(password.getBytes()); + + StringBuilder sb = new StringBuilder(); + for (byte b : hashBytes) { + sb.append(String.format("%02x", b)); + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + 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..24134ba 100644 --- a/src/main/java/dev/service/MenuService.java +++ b/src/main/java/dev/service/MenuService.java @@ -1,12 +1,52 @@ package dev.service; +import dev.dao.MenuItemDao; +import dev.model.MenuItem; + +import java.util.List; + public class MenuService { - public void showMenu() { - - // TODO: - // Display menu items + private final MenuItemDao menuDao; + public MenuService() { + this.menuDao = new MenuItemDao(); } + public void showMenu() { + List items = menuDao.findAll(); + + if (items.isEmpty()) { + System.out.println("No menu items available!"); + return; + } + + System.out.println("\n - Remy's Today Menu -\n"); + + String currentCategory = ""; + for (MenuItem item : items) { + String category = item.getCategory() != null ? item.getCategory() : "Other"; + + if (!category.equals(currentCategory)) { + currentCategory = category; + System.out.println("\n[ " + currentCategory + " ]"); + System.out.println("----------------------------------------"); + } + + System.out.printf("%d. %-25s $%.2f\n", + item.getId(), + item.getName(), + item.getPrice() + ); + } + System.out.println("----------------------------------------\n"); + } + + public List getAllMenuItems() { + return menuDao.findAll(); + } + + public MenuItem getMenuItemById(int id) { + return menuDao.findById(id); + } } \ 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..d348a35 100644 --- a/src/main/java/dev/service/OrderService.java +++ b/src/main/java/dev/service/OrderService.java @@ -1,26 +1,202 @@ 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.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + public class OrderService { + private final MenuItemDao menuDao; + private final OrderDao orderDao; + private final OrderDetailDao detailDao; + private final Scanner scanner; + + public OrderService() { + this.menuDao = new MenuItemDao(); + this.orderDao = new OrderDao(); + this.detailDao = new OrderDetailDao(); + this.scanner = new Scanner(System.in); + } public void placeOrder(int userId) { - // TODO: - // Create order + System.out.println(" [Placing Order]"); + List menuItems = menuDao.findAll(); + if (menuItems.isEmpty()) { + System.out.println("No menu items available!"); + return; + } + + MenuService menuService = new MenuService(); + menuService.showMenu(); + + List orderDetails = new ArrayList<>(); + double totalPrice = 0.0; + + while (true) { + System.out.print("\nEnter item ID (or 0 to finish): "); + int itemId = scanner.nextInt(); + + if (itemId == 0) { + if (orderDetails.isEmpty()) { + System.out.println("Cannot place empty order!"); + return; + } + break; + } + + MenuItem selectedItem = null; + for (MenuItem item : menuItems) { + if (item.getId() == itemId) { + selectedItem = item; + break; + } + } + + if (selectedItem == null) { + System.out.println("Invalid item ID! Please try again."); + continue; + } + + System.out.print("Enter quantity: "); + int quantity = scanner.nextInt(); + + if (quantity <= 0) { + System.out.println("Quantity must be greater than 0!"); + continue; + } + + OrderDetail detail = new OrderDetail(); + detail.setMenuItemId(selectedItem.getId()); + detail.setQuantity(quantity); + detail.setPrice(selectedItem.getPrice()); + detail.setItemName(selectedItem.getName()); + + orderDetails.add(detail); + + double subtotal = selectedItem.getPrice() * quantity; + totalPrice += subtotal; + + System.out.printf("Added %dx %s ($%.2f)\n", + quantity, selectedItem.getName(), subtotal); + } + + Order order = new Order(); + order.setUserId(userId); + order.setCreatedAt(new Timestamp(System.currentTimeMillis())); + order.setTotalPrice(totalPrice); + + int orderId = orderDao.save(order); + if (orderId == -1) { + System.out.println("Failed to save order!"); + return; + } + + for (OrderDetail detail : orderDetails) { + detail.setOrderId(orderId); + detailDao.save(detail); + } + + System.out.println("\nOrder placed successfully! Order #" + orderId); + printReceipt(orderId); } public void printReceipt(int orderId) { + List details = detailDao.findByOrderId(orderId); - // TODO: - // Print order receipt + if (details.isEmpty()) { + System.out.println("Order not found or has no items!"); + return; + } + Order order = orderDao.findById(orderId); + if (order == null) { + System.out.println("Order not found!"); + return; + } + + System.out.println("\n========================================"); + System.out.println(" ORDER RECEIPT"); + System.out.println("========================================"); + System.out.println("Order #: " + orderId); + System.out.println("Date: " + order.getCreatedAt()); + System.out.println("----------------------------------------"); + System.out.printf("%-5s %-20s %-10s %-10s %-10s\n", + "ID", "Item", "Qty", "Price", "Subtotal"); + System.out.println("----------------------------------------"); + + double grandTotal = 0.0; + for (OrderDetail detail : details) { + double subtotal = detail.getPrice() * detail.getQuantity(); + grandTotal += subtotal; + + String itemName = detail.getItemName() != null ? + detail.getItemName() : "Item #" + detail.getMenuItemId(); + + System.out.printf("%-5d %-20s %-10d $%-9.2f $%-9.2f\n", + detail.getMenuItemId(), + itemName, + detail.getQuantity(), + detail.getPrice(), + subtotal + ); + } + + System.out.println("----------------------------------------"); + System.out.printf("%-47s $%-9.2f\n", "GRAND TOTAL:", grandTotal); + System.out.println("========================================"); + System.out.println(" Thank you for your order!"); + System.out.println("========================================\n"); } public void showOrderHistory(int userId) { + System.out.println("\n========================================"); + System.out.println(" ORDER HISTORY"); + System.out.println("========================================\n"); - // TODO: - // Display user's order history + List orders = orderDao.findByUserId(userId); + if (orders.isEmpty()) { + System.out.println("No orders found."); + return; + } + + System.out.println("You have " + orders.size() + " order(s):\n"); + System.out.printf("%-10s %-25s %-10s %-10s\n", + "Order #", "Date", "Items", "Total"); + System.out.println("------------------------------------------------------------"); + + for (Order order : orders) { + List details = detailDao.findByOrderId(order.getId()); + + int itemCount = 0; + for (OrderDetail detail : details) { + itemCount += detail.getQuantity(); + } + + System.out.printf("%-10d %-25s %-10d $%-9.2f\n", + order.getId(), + order.getCreatedAt().toString().substring(0, 19), + itemCount, + order.getTotalPrice() + ); + } + + System.out.println("------------------------------------------------------------\n"); + + System.out.print("Enter order ID to view details (or 0 to return): "); + int orderId = scanner.nextInt(); + + if (orderId > 0) { + printReceipt(orderId); + } } - } \ 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..04b52a0 100644 --- a/src/main/java/dev/ui/ConsoleMenu.java +++ b/src/main/java/dev/ui/ConsoleMenu.java @@ -1,44 +1,130 @@ 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 { - private final Scanner scanner = - new Scanner(System.in); - - 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"); - - } - - } + private final Scanner scanner = new Scanner(System.in); + private final AuthService authService; + private final MenuService menuService; + private final OrderService orderService; + private User currentUser; + public ConsoleMenu() { + this.authService = new AuthService(); + this.menuService = new MenuService(); + this.orderService = new OrderService(); } + public void start() { + while (true) { + if (currentUser == null) { + showAuthMenu(); + } else { + showMainMenu(); + } + } + } + + private void showAuthMenu() { + System.out.println(); + System.out.println(" ===== JAVA PIZZERIA ====="); + System.out.println("1. Login"); + System.out.println("2. Register New Account"); + System.out.println("3. Exit"); + System.out.print("Choose an option: "); + + int choice = scanner.nextInt(); + scanner.nextLine(); + + switch (choice) { + case 1: + login(); + break; + case 2: + register(); + break; + case 3: + System.out.println("Goodbye!"); + System.exit(0); + break; + default: + System.out.println("Invalid choice!"); + } + } + + private void showMainMenu() { + System.out.println(); + System.out.println(" MAIN MENU"); + System.out.println("1. View Menu"); + System.out.println("2. Place a New Order"); + System.out.println("3. View Order History"); + System.out.println("4. Logout"); + System.out.print("Choose an option: "); + + int choice = scanner.nextInt(); + scanner.nextLine(); + + switch (choice) { + case 1: + menuService.showMenu(); + break; + case 2: + orderService.placeOrder(currentUser.getId()); + break; + case 3: + orderService.showOrderHistory(currentUser.getId()); + break; + case 4: + logout(); + break; + default: + System.out.println("Invalid choice!"); + } + } + + private void login() { + System.out.println("\n[Login]"); + 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) { + currentUser = user; + } + } + + private void register() { + System.out.println("\n[Register]"); + System.out.print("Enter username: "); + String username = scanner.nextLine(); + + System.out.print("Enter password: "); + String password = scanner.nextLine(); + + System.out.print("Enter email (optional): "); + String email = scanner.nextLine(); + + if (email == null || email.trim().isEmpty()) { + email = null; + } + + boolean success = authService.register(username, password, email); + if (success) { + System.out.println("Please login with your new account."); + } + } + + private void logout() { + System.out.println("Goodbye, " + currentUser.getUsername() + "!"); + currentUser = null; + } } \ No newline at end of file -- 2.54.0