Develop #1
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
+17
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||
<data-source source="LOCAL" name="postgres@localhost" uuid="c99a2d90-b53b-4858-a6ca-ed633fd94622">
|
||||
<driver-ref>postgresql</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
|
||||
<jdbc-url>jdbc:postgresql://localhost:5432/postgres</jdbc-url>
|
||||
<jdbc-additional-properties>
|
||||
<property name="com.intellij.clouds.kubernetes.db.host.port" />
|
||||
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
|
||||
<property name="com.intellij.clouds.kubernetes.db.container.port" />
|
||||
</jdbc-additional-properties>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
</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>
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="SqlNoDataSourceInspection" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
</profile>
|
||||
</component>
|
||||
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="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>
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Central Repository" />
|
||||
<option name="url" value="https://mirror-maven.runflare.com/maven2" />
|
||||
</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="23" project-jdk-type="JavaSDK" />
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="SqlDialectMappings">
|
||||
<file url="file://$PROJECT_DIR$/database.sql" dialect="GenericSQL" />
|
||||
</component>
|
||||
</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>
|
||||
+66
-124
@@ -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 ...;
|
||||
|
||||
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);
|
||||
@@ -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<MenuItem> findAll() {
|
||||
String query = "SELECT uid, name, price, category FROM menu_item ORDER BY uid";
|
||||
List<MenuItem> 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<Order> findByUserId(int userId) {
|
||||
String query = "SELECT uid, user_id, order_date, total_price FROM orders WHERE user_id = ?";
|
||||
List<Order> 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<OrderDetail> 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<OrderDetail> 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<>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)) {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
// TODO:
|
||||
// Validate and register user
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
try {
|
||||
UserDao userDao = new UserDao();
|
||||
|
||||
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) {
|
||||
|
||||
// TODO:
|
||||
// Authenticate user
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
try {
|
||||
UserDao userDao = new UserDao();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<MenuItem> 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<MenuItem> getAllMenuItems() {
|
||||
return menuDao.findAll();
|
||||
}
|
||||
|
||||
public MenuItem getMenuItemById(int id) {
|
||||
return menuDao.findById(id);
|
||||
}
|
||||
}
|
||||
@@ -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<MenuItem> menuItems = menuDao.findAll();
|
||||
if (menuItems.isEmpty()) {
|
||||
System.out.println("No menu items available!");
|
||||
return;
|
||||
}
|
||||
|
||||
MenuService menuService = new MenuService();
|
||||
menuService.showMenu();
|
||||
|
||||
List<OrderDetail> 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<OrderDetail> 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<Order> 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<OrderDetail> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
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(" ===== JAVA PIZZERIA =====");
|
||||
System.out.println("1. Login");
|
||||
System.out.println("2. Register");
|
||||
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:
|
||||
// TODO
|
||||
login();
|
||||
break;
|
||||
|
||||
case 2:
|
||||
// TODO
|
||||
register();
|
||||
break;
|
||||
|
||||
case 3:
|
||||
return;
|
||||
|
||||
System.out.println("Goodbye!");
|
||||
System.exit(0);
|
||||
break;
|
||||
default:
|
||||
System.out.println("Invalid choice");
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user