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