Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c93d1b89a2 |
Generated
+10
@@ -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/
|
||||
Generated
+13
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<annotationProcessing>
|
||||
<profile name="Maven default annotation processors profile" enabled="true">
|
||||
<sourceOutputDir name="target/generated-sources/annotations" />
|
||||
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
|
||||
<outputRelativeToContentRoot value="true" />
|
||||
<module name="WS-10-Database" />
|
||||
</profile>
|
||||
</annotationProcessing>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding">
|
||||
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+20
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RemoteRepositoriesConfiguration">
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Central Repository" />
|
||||
<option name="url" value="https://repo.maven.apache.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Maven Central repository" />
|
||||
<option name="url" value="https://repo1.maven.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="jboss.community" />
|
||||
<option name="name" value="JBoss Community repository" />
|
||||
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
|
||||
</remote-repository>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+12
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="MavenProjectsManager">
|
||||
<option name="originalFiles">
|
||||
<list>
|
||||
<option value="$PROJECT_DIR$/pom.xml" />
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="25" project-jdk-type="JavaSDK" />
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
+35
-122
@@ -1,141 +1,54 @@
|
||||
-- Restaurant Database Management System
|
||||
--
|
||||
-- Instructions:
|
||||
-- 1. Create all required tables.
|
||||
-- 2. Design appropriate PRIMARY KEY and FOREIGN KEY relationships.
|
||||
-- 3. Add suitable constraints based on the requirements.
|
||||
-- 4. Insert initial mock data.
|
||||
-- 5. Insert at least 3 menu items.
|
||||
-- 6. The script should be executable from start to finish without errors.
|
||||
|
||||
|
||||
|
||||
-- =======================================================
|
||||
-- USER TABLE
|
||||
-- =======================================================
|
||||
--
|
||||
-- Represents customers using the system.
|
||||
--
|
||||
-- Required information:
|
||||
-- - Unique identifier
|
||||
-- - Username
|
||||
-- - Password
|
||||
-- - Email (optional)
|
||||
--
|
||||
-- Requirements:
|
||||
-- - Each user must have a unique identifier.
|
||||
-- - Usernames must be unique.
|
||||
-- - Username and password are required.
|
||||
-- - Passwords should not be stored in plain text.
|
||||
--
|
||||
-- CREATE TABLE ...
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
username VARCHAR(50) NOT NULL UNIQUE,
|
||||
password VARCHAR(256) 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 IF NOT EXISTS menu_items (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
price DECIMAL(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 IF NOT EXISTS orders (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
total_price DECIMAL(10, 2) NOT NULL CHECK (total_price >= 0),
|
||||
CONSTRAINT fk_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 IF NOT EXISTS 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 DECIMAL(10, 2) NOT NULL CHECK (price >= 0),
|
||||
CONSTRAINT fk_order FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_menu_item FOREIGN KEY (menu_item_id) REFERENCES menu_items(id) ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
-- =======================================================
|
||||
-- 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 ...;
|
||||
INSERT INTO menu_items (name, description, price, category) VALUES
|
||||
('Margherita Pizza', 'Classic tomato sauce, fresh mozzarella, and basil', 10.00, 'Pizza'),
|
||||
('Cheeseburger', 'Beef patty, cheddar cheese, lettuce, tomato, and burger sauce', 8.00, 'Burger'),
|
||||
('Fettuccine Alfredo', 'Rich and creamy parmesan sauce over pasta', 12.00, 'Pasta'),
|
||||
('Coca Cola', 'Chilled carbonated soft drink', 2.50, 'Drink')
|
||||
ON CONFLICT DO NOTHING;
|
||||
@@ -1,25 +1,53 @@
|
||||
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 List<MenuItem> findAll() {
|
||||
|
||||
// TODO:
|
||||
// Retrieve all menu items
|
||||
|
||||
return null;
|
||||
List<MenuItem> items = new ArrayList<>();
|
||||
String sql = "SELECT * FROM menu_items ORDER BY id";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet rs = stmt.executeQuery(sql)) {
|
||||
while (rs.next()) {
|
||||
items.add(new MenuItem(
|
||||
rs.getInt("id"),
|
||||
rs.getString("name"),
|
||||
rs.getString("description"),
|
||||
rs.getDouble("price"),
|
||||
rs.getString("category")
|
||||
));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Database error while fetching menu items: " + e.getMessage());
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
public MenuItem findById(int id) {
|
||||
|
||||
// TODO:
|
||||
// Find menu item by id
|
||||
|
||||
String sql = "SELECT * FROM menu_items WHERE id = ?";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setInt(1, id);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
return new MenuItem(
|
||||
rs.getInt("id"),
|
||||
rs.getString("name"),
|
||||
rs.getString("description"),
|
||||
rs.getDouble("price"),
|
||||
rs.getString("category")
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Database error while finding menu item: " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,25 +1,52 @@
|
||||
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) {
|
||||
|
||||
// TODO:
|
||||
// Insert order and return generated id
|
||||
String sql = "INSERT INTO orders (user_id, total_price) VALUES (?, ?)";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
|
||||
stmt.setInt(1, order.getUserId());
|
||||
stmt.setDouble(2, order.getTotalPrice());
|
||||
stmt.executeUpdate();
|
||||
|
||||
try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
|
||||
if (generatedKeys.next()) {
|
||||
return generatedKeys.getInt(1);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Database error while saving order: " + e.getMessage());
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public List<Order> findByUserId(int userId) {
|
||||
|
||||
// TODO:
|
||||
// Retrieve all orders of a user
|
||||
|
||||
return null;
|
||||
List<Order> orders = new ArrayList<>();
|
||||
String sql = "SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setInt(1, userId);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
orders.add(new Order(
|
||||
rs.getInt("id"),
|
||||
rs.getInt("user_id"),
|
||||
rs.getTimestamp("created_at").toLocalDateTime(),
|
||||
rs.getDouble("total_price")
|
||||
));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Database error while searching history: " + e.getMessage());
|
||||
}
|
||||
return orders;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,24 +1,47 @@
|
||||
package dev.dao;
|
||||
|
||||
import dev.database.DatabaseConnection;
|
||||
import dev.model.OrderDetail;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class OrderDetailDao {
|
||||
|
||||
public void save(OrderDetail detail) {
|
||||
|
||||
// TODO:
|
||||
// Insert order detail
|
||||
|
||||
String sql = "INSERT INTO order_details (order_id, menu_item_id, quantity, price) VALUES (?, ?, ?, ?)";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setInt(1, detail.getOrderId());
|
||||
stmt.setInt(2, detail.getMenuItemId());
|
||||
stmt.setInt(3, detail.getQuantity());
|
||||
stmt.setDouble(4, detail.getPrice());
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Database error while saving order details: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public List<OrderDetail> findByOrderId(int orderId) {
|
||||
|
||||
// TODO:
|
||||
// Retrieve order details
|
||||
|
||||
return null;
|
||||
List<OrderDetail> details = new ArrayList<>();
|
||||
String sql = "SELECT * FROM order_details WHERE order_id = ?";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setInt(1, orderId);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
details.add(new OrderDetail(
|
||||
rs.getInt("id"),
|
||||
rs.getInt("order_id"),
|
||||
rs.getInt("menu_item_id"),
|
||||
rs.getInt("quantity"), // <-- Use rs.getInt("quantity") here
|
||||
rs.getDouble("price")
|
||||
));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Database error retrieving order details: " + e.getMessage());
|
||||
}
|
||||
return details;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,23 +1,43 @@
|
||||
package dev.dao;
|
||||
|
||||
import dev.database.DatabaseConnection;
|
||||
import dev.model.User;
|
||||
import java.sql.*;
|
||||
|
||||
public class UserDao {
|
||||
|
||||
public boolean save(User user) {
|
||||
|
||||
// TODO:
|
||||
// Insert user into database
|
||||
|
||||
return false;
|
||||
String sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setString(1, user.getUsername());
|
||||
stmt.setString(2, user.getPassword());
|
||||
stmt.setString(3, user.getEmail());
|
||||
return stmt.executeUpdate() > 0;
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Database error while registering: " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public User findByUsername(String username) {
|
||||
|
||||
// TODO:
|
||||
// Find a user by username
|
||||
|
||||
String sql = "SELECT * FROM users WHERE username = ?";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setString(1, username);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
return new User(
|
||||
rs.getInt("id"),
|
||||
rs.getString("username"),
|
||||
rs.getString("password"),
|
||||
rs.getString("email")
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.err.println("Database error while finding user: " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +1,19 @@
|
||||
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 USER = "postgres"; // Your Username
|
||||
|
||||
private static final String PASSWORD = "password"; // Your Password
|
||||
private static final String URL = "jdbc:postgresql://localhost:5432/restaurant_db";
|
||||
private static final String USER = "postgres";
|
||||
private static final String PASSWORD = "2357";
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,15 +1,30 @@
|
||||
package dev.model;
|
||||
|
||||
public class MenuItem {
|
||||
|
||||
private int id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String description;
|
||||
|
||||
private double price;
|
||||
|
||||
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; }
|
||||
}
|
||||
@@ -5,11 +5,24 @@ import java.time.LocalDateTime;
|
||||
public class Order {
|
||||
|
||||
private int id;
|
||||
|
||||
private int userId;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
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; }
|
||||
}
|
||||
@@ -1,15 +1,30 @@
|
||||
package dev.model;
|
||||
|
||||
public class OrderDetail {
|
||||
|
||||
private int id;
|
||||
|
||||
private int orderId;
|
||||
|
||||
private int menuItemId;
|
||||
|
||||
private int quantity;
|
||||
|
||||
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; }
|
||||
}
|
||||
@@ -1,13 +1,26 @@
|
||||
package dev.model;
|
||||
|
||||
public class User {
|
||||
|
||||
private int id;
|
||||
|
||||
private String username;
|
||||
|
||||
private String password;
|
||||
|
||||
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; }
|
||||
}
|
||||
@@ -1,23 +1,47 @@
|
||||
package dev.service;
|
||||
|
||||
import dev.dao.UserDao;
|
||||
import dev.model.User;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
public class AuthService {
|
||||
|
||||
private final UserDao userDao = new UserDao();
|
||||
public boolean register(String username, String password, String email) {
|
||||
|
||||
// TODO:
|
||||
// Validate and register user
|
||||
|
||||
return false;
|
||||
if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (userDao.findByUsername(username) != null) {
|
||||
System.out.println("Username already exists!");
|
||||
return false;
|
||||
}
|
||||
String hashedPassword = hashPassword(password);
|
||||
User user = new User(0, username, hashedPassword, email);
|
||||
return userDao.save(user);
|
||||
}
|
||||
|
||||
public User login(String username, String password) {
|
||||
|
||||
// TODO:
|
||||
// Authenticate user
|
||||
|
||||
User user = userDao.findByUsername(username);
|
||||
if (user != null && user.getPassword().equals(hashPassword(password))) {
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String hashPassword(String password) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] encodedhash = digest.digest(password.getBytes());
|
||||
StringBuilder hexString = new StringBuilder();
|
||||
for (byte b : encodedhash) {
|
||||
String hex = Integer.toHexString(0xff & b);
|
||||
if (hex.length() == 1) hexString.append('0');
|
||||
hexString.append(hex);
|
||||
}
|
||||
return hexString.toString();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException("Error securely processing password.", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +1,22 @@
|
||||
package dev.service;
|
||||
|
||||
import dev.dao.MenuItemDao;
|
||||
import dev.model.MenuItem;
|
||||
import java.util.List;
|
||||
|
||||
public class MenuService {
|
||||
|
||||
private final MenuItemDao menuItemDao = new MenuItemDao();
|
||||
|
||||
public void showMenu() {
|
||||
|
||||
// TODO:
|
||||
// Display menu items
|
||||
|
||||
List<MenuItem> items = menuItemDao.findAll();
|
||||
System.out.println("\n--- MENU ---");
|
||||
System.out.printf("%-4s | %-20s | %-40s | %-8s | %-10s\n", "ID", "Name", "Description", "Price", "Category");
|
||||
System.out.println("-".repeat(90));
|
||||
for (MenuItem item : items) {
|
||||
System.out.printf("%-4d | %-20s | %-40s | $%-7.2f | %-10s\n",
|
||||
item.getId(), item.getName(), item.getDescription(), item.getPrice(), item.getCategory());
|
||||
}
|
||||
System.out.println("-".repeat(90));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +1,127 @@
|
||||
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.util.*;
|
||||
|
||||
public class OrderService {
|
||||
|
||||
private final MenuItemDao menuItemDao = new MenuItemDao();
|
||||
private final OrderDao orderDao = new OrderDao();
|
||||
private final OrderDetailDao orderDetailDao = new OrderDetailDao();
|
||||
private final Scanner scanner = new Scanner(System.in);
|
||||
|
||||
public void placeOrder(int userId) {
|
||||
Map<Integer, Integer> cart = new HashMap<>(); // MenuItemID -> Quantity
|
||||
|
||||
// TODO:
|
||||
// Create order
|
||||
while (true) {
|
||||
System.out.print("Enter the ID of the item to add (or 0 to complete order): ");
|
||||
int itemId = scanner.nextInt();
|
||||
if (itemId == 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
MenuItem item = menuItemDao.findById(itemId);
|
||||
if (item == null) {
|
||||
System.out.println("Invalid Menu Item ID! Try again.");
|
||||
continue;
|
||||
}
|
||||
|
||||
System.out.print("Enter quantity: ");
|
||||
int qty = scanner.nextInt();
|
||||
if (qty <= 0) {
|
||||
System.out.println("Quantity must be greater than zero!");
|
||||
continue;
|
||||
}
|
||||
|
||||
cart.put(itemId, cart.getOrDefault(itemId, 0) + qty);
|
||||
System.out.println("Added " + qty + "x " + item.getName() + " to cart.");
|
||||
}
|
||||
|
||||
if (cart.isEmpty()) {
|
||||
System.out.println("Cart is empty. Order cancelled.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Calculate Grand Total
|
||||
double grandTotal = 0;
|
||||
List<OrderDetail> details = new ArrayList<>();
|
||||
for (Map.Entry<Integer, Integer> entry : cart.entrySet()) {
|
||||
MenuItem item = menuItemDao.findById(entry.getKey());
|
||||
double subTotal = item.getPrice() * entry.getValue();
|
||||
grandTotal += subTotal;
|
||||
|
||||
OrderDetail detail = new OrderDetail();
|
||||
detail.setMenuItemId(item.getId());
|
||||
detail.setQuantity(entry.getValue());
|
||||
detail.setPrice(item.getPrice()); // Secure current purchase price
|
||||
details.add(detail);
|
||||
}
|
||||
|
||||
// Persist Order
|
||||
Order order = new Order();
|
||||
order.setUserId(userId);
|
||||
order.setTotalPrice(grandTotal);
|
||||
int orderId = orderDao.save(order);
|
||||
|
||||
if (orderId == -1) {
|
||||
System.out.println("An issue occurred. Order could not be created.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Persist Order Details
|
||||
for (OrderDetail detail : details) {
|
||||
detail.setOrderId(orderId);
|
||||
orderDetailDao.save(detail);
|
||||
}
|
||||
|
||||
System.out.println("\nOrder registered successfully!");
|
||||
printReceipt(orderId);
|
||||
}
|
||||
|
||||
public void printReceipt(int orderId) {
|
||||
List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
|
||||
if (details == null || details.isEmpty()) {
|
||||
System.out.println("Receipt not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO:
|
||||
// Print order receipt
|
||||
System.out.println("\n=======================================");
|
||||
System.out.println(" 🧾 ORDER RECEIPT ");
|
||||
System.out.println("=======================================");
|
||||
System.out.printf("%-20s %-5s %-8s %-8s\n", "Item", "Qty", "Unit", "Total");
|
||||
System.out.println("-".repeat(43));
|
||||
|
||||
double total = 0;
|
||||
for (OrderDetail detail : details) {
|
||||
MenuItem item = menuItemDao.findById(detail.getMenuItemId());
|
||||
double lineTotal = detail.getPrice() * detail.getQuantity();
|
||||
total += lineTotal;
|
||||
System.out.printf("%-20s %-5d $%-7.2f $%-7.2f\n",
|
||||
item.getName(), detail.getQuantity(), detail.getPrice(), lineTotal);
|
||||
}
|
||||
System.out.println("-".repeat(43));
|
||||
System.out.printf("Final Total: $%-7.2f\n", total);
|
||||
System.out.println("=======================================\n");
|
||||
}
|
||||
|
||||
public void showOrderHistory(int userId) {
|
||||
List<Order> orders = orderDao.findByUserId(userId);
|
||||
if (orders == null || orders.isEmpty()) {
|
||||
System.out.println("No past orders found.");
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO:
|
||||
// Display user's order history
|
||||
|
||||
System.out.println("\n=== PAST ORDERS ===");
|
||||
for (Order o : orders) {
|
||||
System.out.printf("Order #%d | Date: %s | Total Spent: $%.2f\n",
|
||||
o.getId(), o.getCreatedAt().toString(), o.getTotalPrice());
|
||||
}
|
||||
System.out.println("===================\n");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,44 +1,122 @@
|
||||
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);
|
||||
private final Scanner scanner = new Scanner(System.in);
|
||||
private final AuthService authService = new AuthService();
|
||||
private final MenuService menuService = new MenuService();
|
||||
private final OrderService orderService = new OrderService();
|
||||
|
||||
private User currentUser = null;
|
||||
|
||||
public void start() {
|
||||
|
||||
while (true) {
|
||||
|
||||
System.out.println();
|
||||
System.out.println("===== JAVA PIZZERIA =====");
|
||||
System.out.println("1. Login");
|
||||
System.out.println("2. Register");
|
||||
System.out.println("3. Exit");
|
||||
|
||||
int choice = scanner.nextInt();
|
||||
|
||||
switch (choice) {
|
||||
|
||||
case 1:
|
||||
// TODO
|
||||
break;
|
||||
|
||||
case 2:
|
||||
// TODO
|
||||
break;
|
||||
|
||||
case 3:
|
||||
return;
|
||||
|
||||
default:
|
||||
System.out.println("Invalid choice");
|
||||
|
||||
if (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");
|
||||
System.out.println("3. Exit");
|
||||
System.out.print("Choose an option: ");
|
||||
|
||||
int choice = scanner.nextInt();
|
||||
scanner.nextLine(); // Clear buffer
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
handleLogin();
|
||||
break;
|
||||
case 2:
|
||||
handleRegister();
|
||||
break;
|
||||
case 3:
|
||||
System.out.println("Goodbye!");
|
||||
System.exit(0);
|
||||
default:
|
||||
System.out.println("Invalid choice");
|
||||
}
|
||||
}
|
||||
|
||||
private void showMainMenu() {
|
||||
System.out.println();
|
||||
System.out.println("===== " + currentUser.getUsername().toUpperCase() + "'S PORTAL =====");
|
||||
System.out.println("1. View Menu");
|
||||
System.out.println("2. Place New Order");
|
||||
System.out.println("3. Order History");
|
||||
System.out.println("4. Logout");
|
||||
System.out.print("Choose an option: ");
|
||||
|
||||
int choice = scanner.nextInt();
|
||||
scanner.nextLine(); // Clear buffer
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
menuService.showMenu();
|
||||
break;
|
||||
case 2:
|
||||
menuService.showMenu();
|
||||
orderService.placeOrder(currentUser.getId());
|
||||
break;
|
||||
case 3:
|
||||
orderService.showOrderHistory(currentUser.getId());
|
||||
break;
|
||||
case 4:
|
||||
System.out.println("Logging out...");
|
||||
currentUser = null;
|
||||
break;
|
||||
default:
|
||||
System.out.println("Invalid choice");
|
||||
}
|
||||
}
|
||||
|
||||
private void handleLogin() {
|
||||
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;
|
||||
System.out.println("Login successful! Welcome, " + user.getUsername());
|
||||
} else {
|
||||
System.out.println("Invalid username or password!");
|
||||
}
|
||||
}
|
||||
|
||||
private void handleRegister() {
|
||||
System.out.println("\n[Registration]");
|
||||
System.out.print("Enter a unique username: ");
|
||||
String username = scanner.nextLine();
|
||||
System.out.print("Enter password: ");
|
||||
String password = scanner.nextLine();
|
||||
System.out.print("Enter email (Optional, press Enter to skip): ");
|
||||
String email = scanner.nextLine();
|
||||
if (email.trim().isEmpty()) {
|
||||
email = null;
|
||||
}
|
||||
|
||||
boolean success = authService.register(username, password, email);
|
||||
if (success) {
|
||||
System.out.println("Registration successful! You can now log in.");
|
||||
} else {
|
||||
System.out.println("Registration failed. Try a different username.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user