1 Commits
Author SHA1 Message Date
avasanatkar cc82879fcc adding codes 2026-06-22 23:19:56 +03:30
22 changed files with 796 additions and 155 deletions
+10
View File
@@ -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/
+13
View File
@@ -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>
+7
View File
@@ -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
View File
@@ -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>
+20
View File
@@ -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://maven.devneeds.ir/" />
</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>
+12
View File
@@ -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" languageLevel="JDK_23" default="true" project-jdk-name="23" project-jdk-type="JavaSDK" />
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
+125 -124
View File
@@ -1,141 +1,142 @@
-- 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.
-- =========================================================
-- WS 10 - Restaurant Database Management System
-- database.sql
-- =========================================================
-- Drop tables if they already exist (useful when re-running the script)
DROP TABLE IF EXISTS order_details;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS menu_items;
DROP TABLE IF EXISTS users;
-- ======================================================= -- =========================================================
-- USER TABLE -- 1. USERS (Customer)
-- ======================================================= -- =========================================================
-- CREATE TABLE users (
-- Represents customers using the system. id BIGSERIAL NOT NULL PRIMARY KEY,
-- username VARCHAR(50) NOT NULL UNIQUE,
-- Required information: password_hash VARCHAR(255) NOT NULL,
-- - Unique identifier email VARCHAR(100)
-- - 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 ...
-- =========================================================
-- 2. MENU_ITEMS
-- =========================================================
CREATE TABLE menu_items (
id BIGSERIAL NOT NULL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description VARCHAR(255),
price NUMERIC(10, 2) NOT NULL CHECK (price > 0),
category VARCHAR(50)
);
-- =========================================================
-- 3. ORDERS
-- =========================================================
CREATE TABLE orders (
id BIGSERIAL NOT NULL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id),
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
total_price NUMERIC(10, 2) NOT NULL CHECK (total_price >= 0)
);
-- ======================================================= -- =========================================================
-- MENU ITEM TABLE -- 4. ORDER_DETAILS (items inside an order)
-- ======================================================= -- =========================================================
-- CREATE TABLE order_details (
-- Represents available food and drink items. id BIGSERIAL NOT NULL PRIMARY KEY,
-- order_id BIGINT NOT NULL REFERENCES orders (id),
-- Required information: menu_item_id BIGINT NOT NULL REFERENCES menu_items (id),
-- - Unique identifier quantity INT NOT NULL CHECK (quantity > 0),
-- - Name unit_price NUMERIC(10, 2) NOT NULL CHECK (unit_price > 0)
-- - Description (optional) );
-- - Price
-- - Category (optional)
--
-- Requirements:
-- - Each menu item must have a unique identifier.
-- - Name is required.
-- - Price must always be positive.
--
-- CREATE TABLE ...
-- =========================================================
-- Initial mock data
-- =========================================================
-- Sample users
-- NOTE: these password_hash values are just placeholders.
-- Your Java app must hash real passwords before inserting (e.g. with BCrypt).
INSERT INTO users (username, password_hash, email) VALUES
('john_doe', '$2a$10$placeholderHashValue1234567890', 'john@example.com'),
('jane_smith', '$2a$10$placeholderHashValue1234567891', 'jane@example.com');
-- ======================================================= -- Sample menu items (at least 3 required)
-- ORDER TABLE INSERT INTO menu_items (name, description, price, category) VALUES
-- ======================================================= ('Pizza Margherita', 'Classic pizza with tomato, mozzarella and basil', 10.00, 'Main'),
-- ('Cheeseburger', 'Beef patty with cheddar cheese and house sauce', 8.00, 'Main'),
-- Represents orders placed by customers. ('Pasta Carbonara', 'Pasta with egg, pancetta and parmesan', 12.00, 'Main'),
-- ('Tiramisu', 'Traditional Italian coffee-flavored dessert', 6.50, 'Dessert'),
-- Required information: ('Cola', 'Soft drink, 330ml can', 2.50, 'Drink');-- =========================================================
-- - Unique identifier -- WS 10 - Restaurant Database Management System
-- - Reference to customer -- database.sql
-- - 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 ...
-- Drop tables if they already exist (useful when re-running the script)
DROP TABLE IF EXISTS order_details;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS menu_items;
DROP TABLE IF EXISTS users;
-- =========================================================
-- 1. USERS (Customer)
-- =========================================================
CREATE TABLE users (
id BIGSERIAL NOT NULL PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
email VARCHAR(100)
);
-- ======================================================= -- =========================================================
-- ORDER DETAIL TABLE -- 2. MENU_ITEMS
-- ======================================================= -- =========================================================
-- CREATE TABLE menu_items (
-- Represents items inside an order. id BIGSERIAL NOT NULL PRIMARY KEY,
-- name VARCHAR(100) NOT NULL,
-- Required information: description VARCHAR(255),
-- - Unique identifier price NUMERIC(10, 2) NOT NULL CHECK (price > 0),
-- - Reference to an order category VARCHAR(50)
-- - 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 ...
-- =========================================================
-- 3. ORDERS
-- =========================================================
CREATE TABLE orders (
id BIGSERIAL NOT NULL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id),
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
total_price NUMERIC(10, 2) NOT NULL CHECK (total_price >= 0)
);
-- =========================================================
-- 4. ORDER_DETAILS (items inside an order)
-- =========================================================
CREATE TABLE order_details (
id BIGSERIAL NOT NULL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders (id),
menu_item_id BIGINT NOT NULL REFERENCES menu_items (id),
quantity INT NOT NULL CHECK (quantity > 0),
unit_price NUMERIC(10, 2) NOT NULL CHECK (unit_price > 0)
);
-- ======================================================= -- =========================================================
-- INITIAL MENU DATA -- Initial mock data
-- ======================================================= -- =========================================================
--
-- Insert at least 3 food or drink items.
--
-- Example categories:
-- - Pizza
-- - Burger
-- - Pasta
-- - Drink
--
-- INSERT INTO ...
-- Sample users
-- NOTE: these password_hash values are just placeholders.
-- Your Java app must hash real passwords before inserting (e.g. with BCrypt).
INSERT INTO users (username, password_hash, email) VALUES
('john_doe', '$2a$10$placeholderHashValue1234567890', 'john@example.com'),
('jane_smith', '$2a$10$placeholderHashValue1234567891', 'jane@example.com');
-- Sample menu items (at least 3 required)
-- ======================================================= INSERT INTO menu_items (name, description, price, category) VALUES
-- OPTIONAL TEST DATA ('Pizza Margherita', 'Classic pizza with tomato, mozzarella and basil', 10.00, 'Main'),
-- ======================================================= ('Cheeseburger', 'Beef patty with cheddar cheese and house sauce', 8.00, 'Main'),
-- ('Pasta Carbonara', 'Pasta with egg, pancetta and parmesan', 12.00, 'Main'),
-- You may insert sample users and orders for testing. ('Tiramisu', 'Traditional Italian coffee-flavored dessert', 6.50, 'Dessert'),
-- This section is optional. ('Cola', 'Soft drink, 330ml can', 2.50, 'Drink');
--
-- INSERT INTO ...
-- =======================================================
-- VERIFICATION QUERIES
-- =======================================================
--
-- Uncomment these queries to verify your database.
--
-- SELECT * FROM ...;
-- SELECT * FROM ...;
-- SELECT * FROM ...;
-- SELECT * FROM ...;
+6 -1
View File
@@ -27,6 +27,11 @@
<version>${postgresql.version}</version> <version>${postgresql.version}</version>
</dependency> </dependency>
</dependencies> <dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
</dependencies>
</project> </project>
+49 -1
View File
@@ -1,7 +1,14 @@
package dev.dao; package dev.dao;
import dev.model.MenuItem; import dev.model.MenuItem;
import dev.database.DatabaseConnection;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class MenuItemDao { public class MenuItemDao {
@@ -11,7 +18,23 @@ public class MenuItemDao {
// TODO: // TODO:
// Retrieve all menu items // Retrieve all menu items
return null; // return null;
List<MenuItem> menuItems = new ArrayList<>();
String sql = "SELECT id, name, description, price, category FROM menu_items";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
menuItems.add(mapRowToMenuItem(rs));
}
} catch (SQLException e) {
e.printStackTrace();
}
return menuItems;
} }
public MenuItem findById(int id) { public MenuItem findById(int id) {
@@ -19,7 +42,32 @@ public class MenuItemDao {
// TODO: // TODO:
// Find menu item by id // Find menu item by id
String sql = "SELECT id, name, description, price, category 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 mapRowToMenuItem(rs);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return null; return null;
} }
private MenuItem mapRowToMenuItem(ResultSet rs) throws SQLException {
int id = rs.getInt("id");
String name = rs.getString("name");
String description = rs.getString("description");
BigDecimal price = rs.getBigDecimal("price");
String category = rs.getString("category");
return new MenuItem(id, name, description, price, category);
}
} }
+51 -1
View File
@@ -1,7 +1,16 @@
package dev.dao; package dev.dao;
import dev.model.Order; import dev.model.Order;
import dev.database.DatabaseConnection;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class OrderDao { public class OrderDao {
@@ -10,6 +19,25 @@ public class OrderDao {
// TODO: // TODO:
// Insert order and return generated id // 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.setBigDecimal(2, order.getTotalPrice());
stmt.executeUpdate();
try (ResultSet rs = stmt.getGeneratedKeys()) {
if (rs.next()) {
return rs.getInt(1);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1; return -1;
} }
@@ -18,8 +46,30 @@ public class OrderDao {
// TODO: // TODO:
// Retrieve all orders of a user // Retrieve all orders of a user
List<Order> orders = new ArrayList<>();
String sql = "SELECT id, user_id, created_at, total_price FROM orders WHERE user_id = ?";
return null; try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, userId);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
int uId = rs.getInt("user_id");
Timestamp createdAt = rs.getTimestamp("created_at");
BigDecimal totalPrice = rs.getBigDecimal("total_price");
orders.add(new Order(id, uId, createdAt.toLocalDateTime(), totalPrice));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return orders;
} }
} }
+45 -1
View File
@@ -1,7 +1,14 @@
package dev.dao; package dev.dao;
import dev.model.OrderDetail; import dev.model.OrderDetail;
import dev.database.DatabaseConnection;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class OrderDetailDao { public class OrderDetailDao {
@@ -10,15 +17,52 @@ public class OrderDetailDao {
// TODO: // TODO:
// Insert order detail // Insert order detail
String sql = "INSERT INTO order_details (order_id, menu_item_id, quantity, unit_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.setBigDecimal(4, detail.getPrice());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} }
public List<OrderDetail> findByOrderId(int orderId) { public List<OrderDetail> findByOrderId(int orderId) {
// TODO: // TODO:
// Retrieve order details // Retrieve order details
List<OrderDetail> details = new ArrayList<>();
String sql = "SELECT id, order_id, menu_item_id, quantity, unit_price FROM order_details WHERE order_id = ?";
return null; try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, orderId);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
int oId = rs.getInt("order_id");
int menuItemId = rs.getInt("menu_item_id");
int quantity = rs.getInt("quantity");
BigDecimal price = rs.getBigDecimal("unit_price");
details.add(new OrderDetail(id, oId, menuItemId, quantity, price));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return details;
} }
} }
+41 -1
View File
@@ -1,21 +1,61 @@
package dev.dao; package dev.dao;
import dev.model.User; import dev.model.User;
import dev.database.DatabaseConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao { public class UserDao {
public boolean save(User user) { public boolean save(User user) {
// TODO: // TODO:
// Insert user into database // Insert user into database
String sql = "INSERT INTO users (username, password_hash, email) VALUES (?, ?, ?)";
return false; 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());
stmt.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
} }
public User findByUsername(String username) { public User findByUsername(String username) {
// TODO: // TODO:
// Find a user by username // Find a user by username
String sql = "SELECT id, username, password_hash, email 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()) {
int id = rs.getInt("id");
String uname = rs.getString("username");
String passwordHash = rs.getString("password_hash");
String email = rs.getString("email");
return new User(id, uname, passwordHash, email);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return null; return null;
} }
@@ -1,15 +1,16 @@
package dev.database; package dev.database;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
public class DatabaseConnection { public class DatabaseConnection {
private static final String URL = "jdbc:postgresql://localhost:5432/restaurant_db";
private static final String URL = "jdbc:postgresql://localhost:5432/restaurant_db"; // DB Server private static final String USER = "avasanatkar";
private static final String USER = "postgres"; // Your Username private static final String PASSWORD = "";
private static final String PASSWORD = "password"; // Your Password
private DatabaseConnection() { private DatabaseConnection() {
@@ -21,7 +22,9 @@ public class DatabaseConnection {
// TODO: // TODO:
// Return a valid PostgreSQL connection // Return a valid PostgreSQL connection
return null; // return null;
return DriverManager.getConnection(URL, USER, PASSWORD);
} }
} }
+35 -5
View File
@@ -1,15 +1,45 @@
package dev.model; package dev.model;
import java.math.BigDecimal;
public class MenuItem { public class MenuItem {
private int id; private int id;
private String name; private String name;
private String description; private String description;
private BigDecimal price;
private double price;
private String category; private String category;
public MenuItem() {}
public MenuItem(int id, String name, String description, BigDecimal price, String category) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
this.category = category;
}
public MenuItem(String name, String description, BigDecimal price, String category) {
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 BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
@Override
public String toString() {
return id + ". " + name + " - $" + price + (category != null ? " (" + category + ")" : "");
}
} }
+28 -3
View File
@@ -1,15 +1,40 @@
package dev.model; package dev.model;
import java.math.BigDecimal;
import java.time.LocalDateTime; import java.time.LocalDateTime;
public class Order { public class Order {
private int id; private int id;
private int userId; private int userId;
private LocalDateTime createdAt; private LocalDateTime createdAt;
private BigDecimal totalPrice;
private double totalPrice; public Order() {}
public Order(int id, int userId, LocalDateTime createdAt, BigDecimal totalPrice) {
this.id = id;
this.userId = userId;
this.createdAt = createdAt;
this.totalPrice = totalPrice;
}
public Order(int userId, BigDecimal totalPrice) {
this.userId = userId;
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 BigDecimal getTotalPrice() { return totalPrice; }
public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; }
@Override
public String toString() {
return "Order #" + id + " - " + createdAt + " - Total: $" + totalPrice;
}
} }
+33 -4
View File
@@ -1,15 +1,44 @@
package dev.model; package dev.model;
import java.math.BigDecimal;
public class OrderDetail { public class OrderDetail {
private int id; private int id;
private int orderId; private int orderId;
private int menuItemId; private int menuItemId;
private int quantity; private int quantity;
private BigDecimal price;
private double price; public OrderDetail() {}
public OrderDetail(int id, int orderId, int menuItemId, int quantity, BigDecimal price) {
this.id = id;
this.orderId = orderId;
this.menuItemId = menuItemId;
this.quantity = quantity;
this.price = price;
}
public OrderDetail(int orderId, int menuItemId, int quantity, BigDecimal price) {
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 BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public BigDecimal getSubtotal() {
return price.multiply(BigDecimal.valueOf(quantity));
}
} }
+28 -3
View File
@@ -3,11 +3,36 @@ package dev.model;
public class User { public class User {
private int id; private int id;
private String username; private String username;
private String password; private String password;
private String email; 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 User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
@Override
public String toString() {
return "User{id=" + id + ", username='" + username + "', email='" + email + "'}";
}
} }
+23 -2
View File
@@ -1,21 +1,42 @@
package dev.service; package dev.service;
import dev.model.User; import dev.model.User;
import dev.dao.UserDao;
import org.mindrot.jbcrypt.BCrypt;
public class AuthService { public class AuthService {
private final UserDao userDao = new UserDao();
public boolean register(String username, String password, String email) { public boolean register(String username, String password, String email) {
// TODO: // TODO:
// Validate and register user // Validate and register user
if (username == null || username.isBlank() || password == null || password.isBlank()) {
return false;
}
return false; if (userDao.findByUsername(username) != null) {
return false;
}
String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
User newUser = new User(username, hashedPassword, email);
return userDao.save(newUser);
} }
public User login(String username, String password) { public User login(String username, String password) {
// TODO: // TODO:
// Authenticate user // Authenticate user
User user = userDao.findByUsername(username);
if (user == null) {
return null;
}
if (BCrypt.checkpw(password, user.getPassword())) {
return user;
}
return null; return null;
} }
+19 -1
View File
@@ -1,12 +1,30 @@
package dev.service; package dev.service;
import dev.dao.MenuItemDao;
import dev.model.MenuItem;
import java.util.List;
public class MenuService { public class MenuService {
private final MenuItemDao menuItemDao = new MenuItemDao();
public void showMenu() { public void showMenu() {
// TODO: // TODO:
// Display menu items // Display menu items
List<MenuItem> items = menuItemDao.findAll();
if (items.isEmpty()) {
System.out.println("No menu items available.");
return;
}
System.out.println("=======================================");
System.out.println(" MENU");
System.out.println("=======================================");
for (MenuItem item : items) {
System.out.println(item);
}
System.out.println("=======================================");
} }
} }
+84 -2
View File
@@ -1,26 +1,108 @@
package dev.service; 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.math.BigDecimal;
import java.util.List;
import java.util.Map;
public class OrderService { public class OrderService {
private final OrderDao orderDao = new OrderDao();
private final OrderDetailDao orderDetailDao = new OrderDetailDao();
private final MenuItemDao menuItemDao = new MenuItemDao();
public void placeOrder(int userId) { public int placeOrder(int userId, Map<Integer, Integer> itemQuantities) {
// TODO: // TODO:
// Create order // Create order
if (itemQuantities == null || itemQuantities.isEmpty()) {
return -1;
}
BigDecimal total = BigDecimal.ZERO;
for (Map.Entry<Integer, Integer> entry : itemQuantities.entrySet()) {
MenuItem item = menuItemDao.findById(entry.getKey());
if (item == null) {
continue;
}
int quantity = entry.getValue();
total = total.add(item.getPrice().multiply(BigDecimal.valueOf(quantity)));
}
Order order = new Order(userId, total);
int orderId = orderDao.save(order);
if (orderId == -1) {
return -1;
}
for (Map.Entry<Integer, Integer> entry : itemQuantities.entrySet()) {
MenuItem item = menuItemDao.findById(entry.getKey());
if (item == null) {
continue;
}
int quantity = entry.getValue();
OrderDetail detail = new OrderDetail(orderId, item.getId(), quantity, item.getPrice());
orderDetailDao.save(detail);
}
return orderId;
} }
public void printReceipt(int orderId) { public void printReceipt(int orderId) {
// TODO: // TODO:
// Print order receipt // Print order receipt
List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
if (details.isEmpty()) {
System.out.println("No details found for order #" + orderId);
return;
}
System.out.println("---------------------------------------");
System.out.printf("%-12s %-6s %-10s %-10s%n", "Item", "Qty", "Unit", "Total");
System.out.println("---------------------------------------");
BigDecimal grandTotal = BigDecimal.ZERO;
for (OrderDetail detail : details) {
MenuItem item = menuItemDao.findById(detail.getMenuItemId());
String name = (item != null) ? item.getName() : "Unknown item";
BigDecimal subtotal = detail.getSubtotal();
grandTotal = grandTotal.add(subtotal);
System.out.printf("%-12s %-6d $%-9.2f $%-9.2f%n",
name, detail.getQuantity(), detail.getPrice(), subtotal);
}
System.out.println("---------------------------------------");
System.out.println("Final Total: $" + grandTotal);
} }
public void showOrderHistory(int userId) { public void showOrderHistory(int userId) {
// TODO: // TODO:
// Display user's order history // Display user's order history
List<Order> orders = orderDao.findByUserId(userId);
if (orders.isEmpty()) {
System.out.println("No past orders found.");
return;
}
System.out.println("=======================================");
System.out.println(" ORDER HISTORY");
System.out.println("=======================================");
for (Order order : orders) {
System.out.println(order);
}
} }
} }
+147 -1
View File
@@ -1,12 +1,23 @@
package dev.ui; package dev.ui;
import java.util.Scanner; import java.util.Scanner;
import dev.model.MenuItem;
import dev.model.User;
import dev.service.AuthService;
import dev.service.MenuService;
import dev.service.OrderService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ConsoleMenu { public class ConsoleMenu {
private final Scanner scanner = private final Scanner scanner =
new Scanner(System.in); new Scanner(System.in);
private final AuthService authService = new AuthService();
private final MenuService menuService = new MenuService();
private final OrderService orderService = new OrderService();
public void start() { public void start() {
while (true) { while (true) {
@@ -23,10 +34,12 @@ public class ConsoleMenu {
case 1: case 1:
// TODO // TODO
handleLogin();
break; break;
case 2: case 2:
// TODO // TODO
handleRegister();
break; break;
case 3: case 3:
@@ -40,5 +53,138 @@ public class ConsoleMenu {
} }
} }
private void handleRegister() {
System.out.println();
System.out.println("[Register New Account]");
System.out.print("Choose a username: ");
String username = scanner.next();
System.out.print("Choose a password: ");
String password = scanner.next();
scanner.nextLine();
System.out.print("Email (optional, press enter to skip): ");
String email = scanner.nextLine();
if (email.isBlank()) {
email = null;
}
boolean success = authService.register(username, password, email);
if (success) {
System.out.println("Registration successful! You can now login.");
} else {
System.out.println("Registration failed. Username may already be taken.");
}
}
private void handleLogin() {
System.out.println();
System.out.println("[Login]");
System.out.print("Enter username: ");
String username = scanner.next();
System.out.print("Enter password: ");
String password = scanner.next();
User user = authService.login(username, password);
if (user == null) {
System.out.println("Invalid username or password.");
return;
}
System.out.println("Welcome, " + user.getUsername() + "!");
showMainMenu(user);
}
private void showMainMenu(User user) {
boolean loggedIn = true;
while (loggedIn) {
System.out.println();
System.out.println("=======================================");
System.out.println(" MAIN MENU");
System.out.println("=======================================");
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");
int choice = scanner.nextInt();
switch (choice) {
case 1:
menuService.showMenu();
break;
case 2:
handlePlaceOrder(user);
break;
case 3:
orderService.showOrderHistory(user.getId());
break;
case 4:
loggedIn = false;
System.out.println("Logged out.");
break;
default:
System.out.println("Invalid choice");
}
}
}
private void handlePlaceOrder(User user) {
menuService.showMenu();
Map<Integer, Integer> itemQuantities = new HashMap<>();
System.out.println();
System.out.println("[Placing Order]");
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;
}
System.out.print("Enter quantity: ");
int quantity = scanner.nextInt();
if (quantity <= 0) {
System.out.println("Quantity must be greater than zero.");
continue;
}
itemQuantities.merge(itemId, quantity, Integer::sum);
System.out.println("Added " + quantity + "x item #" + itemId + " to your cart.");
}
if (itemQuantities.isEmpty()) {
System.out.println("No items added. Order cancelled.");
return;
}
int orderId = orderService.placeOrder(user.getId(), itemQuantities);
if (orderId == -1) {
System.out.println("Failed to place order.");
return;
}
System.out.println();
System.out.println("[Order Summary / Receipt]");
orderService.printReceipt(orderId);
System.out.println("Order saved successfully!");
}
} }