Merge pull request 'Restaurant Database Management System' (#1) from develop into main

Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
2026-07-31 20:49:45 +00:00
21 changed files with 806 additions and 234 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>
+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" project-jdk-name="25" 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>
+52 -108
View File
@@ -1,141 +1,85 @@
-- 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 users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
email VARCHAR(100)
);
-- =======================================================
-- MENU ITEM TABLE
-- =======================================================
--
-- Represents available food and drink items.
--
-- Required information:
-- - Unique identifier
-- - Name
-- - Description (optional)
-- - Price
-- - Category (optional)
--
-- Requirements:
-- - Each menu item must have a unique identifier.
-- - Name is required.
-- - Price must always be positive.
--
-- CREATE TABLE ...
CREATE TABLE menu_items (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description TEXT,
price NUMERIC(10,2) NOT NULL CHECK (price > 0),
category VARCHAR(50)
);
-- =======================================================
-- ORDER TABLE
-- ORDERS TABLE
-- =======================================================
--
-- Represents orders placed by customers.
--
-- Required information:
-- - Unique identifier
-- - Reference to customer
-- - Creation date and time
-- - Total price
--
-- Requirements:
-- - Each order must belong to exactly one user.
-- - A user can have multiple orders.
-- - The relationship between User and Order must be implemented.
--
-- Note:
-- Avoid using reserved SQL keywords as table names.
-- Consider using a name such as "orders" or "customer_orders".
--
-- CREATE TABLE ...
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
total_price NUMERIC(10,2) NOT NULL DEFAULT 0,
CONSTRAINT fk_orders_user
FOREIGN KEY (user_id)
REFERENCES users(id)
ON DELETE CASCADE
);
-- =======================================================
-- ORDER DETAIL TABLE
-- =======================================================
--
-- Represents items inside an order.
--
-- Required information:
-- - Unique identifier
-- - Reference to an order
-- - Reference to a menu item
-- - Quantity
-- - Item price at purchase time
--
-- Requirements:
-- - Each detail record must belong to one order.
-- - Each detail record must reference one menu item.
-- - Quantity must always be greater than zero.
-- - Store the item's price at the moment of purchase.
--
-- CREATE TABLE ...
CREATE TABLE order_details (
id SERIAL PRIMARY KEY,
order_id INT NOT NULL,
menu_item_id INT NOT NULL,
quantity INT NOT NULL CHECK (quantity > 0),
price_at_purchase NUMERIC(10,2) NOT NULL,
CONSTRAINT fk_order_details_order
FOREIGN KEY (order_id)
REFERENCES orders(id)
ON DELETE CASCADE,
CONSTRAINT fk_order_details_menu_item
FOREIGN KEY (menu_item_id)
REFERENCES menu_items(id)
);
-- =======================================================
-- INITIAL MENU DATA
-- =======================================================
--
-- Insert at least 3 food or drink items.
--
-- Example categories:
-- - Pizza
-- - Burger
-- - Pasta
-- - Drink
--
-- INSERT INTO ...
INSERT INTO menu_items (name, description, price, category) VALUES
('Margherita Pizza', 'Classic cheese pizza', 10.00, 'Pizza'),
('Cheeseburger', 'Beef burger with cheese', 8.50, 'Burger'),
('Spaghetti Bolognese', 'Pasta with meat sauce', 12.00, 'Pasta'),
('Coca Cola', 'Cold soft drink', 2.50, 'Drink');
-- =======================================================
-- OPTIONAL TEST DATA
-- OPTIONAL TEST USER
-- =======================================================
--
-- You may insert sample users and orders for testing.
-- This section is optional.
--
-- INSERT INTO ...
INSERT INTO users (username, password, email) VALUES
('admin', 'hashed_password_here', 'admin@example.com');
-- =======================================================
-- VERIFICATION QUERIES
-- =======================================================
--
-- Uncomment these queries to verify your database.
--
-- SELECT * FROM ...;
-- SELECT * FROM ...;
-- SELECT * FROM ...;
-- SELECT * FROM ...;
-- SELECT * FROM users;
-- SELECT * FROM menu_items;
-- SELECT * FROM orders;
-- SELECT * FROM order_details;
+37 -4
View File
@@ -1,14 +1,47 @@
package dev;
import dev.dao.MenuItemDao;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.dao.UserDao;
import dev.database.DatabaseConnection;
import dev.service.AuthService;
import dev.service.MenuService;
import dev.service.OrderService;
import dev.ui.ConsoleMenu;
public class Main {
import java.sql.Connection;
public static void main(String[] args) {
public class Main
{
public static void main(String[] args)
{
try
{
Connection connection = DatabaseConnection.getConnection();
UserDao userDao = new UserDao(connection);
MenuItemDao menuItemDao = new MenuItemDao(connection);
OrderDao orderDao = new OrderDao(connection);
OrderDetailDao orderDetailDao = new OrderDetailDao(connection);
AuthService authService = new AuthService(userDao);
MenuService menuService = new MenuService(menuItemDao);
OrderService orderService = new OrderService(
orderDao,
orderDetailDao,
menuItemDao
);
ConsoleMenu menu = new ConsoleMenu(
authService,
menuService,
orderService
);
ConsoleMenu menu = new ConsoleMenu();
menu.start();
}
catch (Exception e) {System.out.println("Application error: " + e.getMessage());}
}
}
+61 -13
View File
@@ -2,24 +2,72 @@ package dev.dao;
import dev.model.MenuItem;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class MenuItemDao {
public class MenuItemDao
{
private final Connection connection;
public List<MenuItem> findAll() {
public MenuItemDao(Connection connection) {this.connection = connection;}
// TODO:
// Retrieve all menu items
public List<MenuItem> findAll()
{
List<MenuItem> items = new ArrayList<>();
String sql = "SELECT id, name, description, price, category FROM menu_items";
try (PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery())
{
while (rs.next())
{
MenuItem item = new MenuItem();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setDescription(rs.getString("description"));
item.setPrice(rs.getDouble("price"));
item.setCategory(rs.getString("category"));
items.add(item);
}
}
catch (SQLException e) {System.out.println("Error fetching menu items: " + e.getMessage());}
return items;
}
public MenuItem findById(int id)
{
String sql = "SELECT id, name, description, price, category FROM menu_items WHERE id = ?";
try (PreparedStatement ps = connection.prepareStatement(sql))
{
ps.setInt(1, id);
try (ResultSet rs = ps.executeQuery())
{
if (rs.next())
{
MenuItem item = new MenuItem();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setDescription(rs.getString("description"));
item.setPrice(rs.getDouble("price"));
item.setCategory(rs.getString("category"));
return item;
}
}
}
catch (SQLException e) {System.out.println("Error finding menu item: " + e.getMessage());}
return null;
}
public MenuItem findById(int id) {
// TODO:
// Find menu item by id
return null;
}
}
+61 -8
View File
@@ -2,24 +2,77 @@ package dev.dao;
import dev.model.Order;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class OrderDao {
public class OrderDao
{
private final Connection connection;
public int save(Order order) {
public OrderDao(Connection connection) {this.connection = connection;}
// TODO:
// Insert order and return generated id
public int save(Order order)
{
String sql = """
INSERT INTO orders (user_id, created_at, total_price)
VALUES (?, ?, ?)
""";
try (PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS))
{
ps.setInt(1, order.getUserId());
ps.setTimestamp(2, Timestamp.valueOf(order.getCreatedAt()));
ps.setDouble(3, order.getTotalPrice());
int affectedRows = ps.executeUpdate();
if (affectedRows == 0) {return -1;}
try (ResultSet generatedKeys = ps.getGeneratedKeys())
{
if (generatedKeys.next()) {return generatedKeys.getInt(1);}
}
}
catch (SQLException e) {System.out.println("Error saving order: " + e.getMessage());}
return -1;
}
public List<Order> findByUserId(int userId) {
public List<Order> findByUserId(int userId)
{
List<Order> orders = new ArrayList<>();
// TODO:
// Retrieve all orders of a user
String sql = """
SELECT id, user_id, created_at, total_price
FROM orders
WHERE user_id = ?
ORDER BY created_at DESC
""";
return null;
try (PreparedStatement ps = connection.prepareStatement(sql))
{
ps.setInt(1, userId);
try (ResultSet rs = ps.executeQuery())
{
while (rs.next())
{
Order order = new Order();
order.setId(rs.getInt("id"));
order.setUserId(rs.getInt("user_id"));
order.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
order.setTotalPrice(rs.getDouble("total_price"));
orders.add(order);
}
}
}
catch (SQLException e) {System.out.println("Error fetching orders: " + e.getMessage());}
return orders;
}
}
+57 -11
View File
@@ -2,23 +2,69 @@ package dev.dao;
import dev.model.OrderDetail;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class OrderDetailDao {
public class OrderDetailDao
{
private final Connection connection;
public void save(OrderDetail detail) {
public OrderDetailDao(Connection connection) {this.connection = connection;}
// TODO:
// Insert order detail
public void save(OrderDetail detail)
{
String sql = """
INSERT INTO order_details (order_id, menu_item_id, quantity, price_at_purchase)
VALUES (?, ?, ?, ?)
""";
try (PreparedStatement ps = connection.prepareStatement(sql))
{
ps.setInt(1, detail.getOrderId());
ps.setInt(2, detail.getMenuItemId());
ps.setInt(3, detail.getQuantity());
ps.setDouble(4, detail.getPrice()); // درست
ps.executeUpdate();
}
public List<OrderDetail> findByOrderId(int orderId) {
// TODO:
// Retrieve order details
return null;
catch (SQLException e) {System.out.println("Error saving order detail: " + e.getMessage());}
}
public List<OrderDetail> findByOrderId(int orderId)
{
List<OrderDetail> details = new ArrayList<>();
String sql = """
SELECT id, order_id, menu_item_id, quantity, price_at_purchase
FROM order_details
WHERE order_id = ?
""";
try (PreparedStatement ps = connection.prepareStatement(sql))
{
ps.setInt(1, orderId);
try (ResultSet rs = ps.executeQuery())
{
while (rs.next())
{
OrderDetail detail = new OrderDetail();
detail.setId(rs.getInt("id"));
detail.setOrderId(rs.getInt("order_id"));
detail.setMenuItemId(rs.getInt("menu_item_id"));
detail.setQuantity(rs.getInt("quantity"));
detail.setPrice(rs.getDouble("price_at_purchase"));
details.add(detail);
}
}
}
catch (SQLException e) {System.out.println("Error fetching order details: " + e.getMessage());}
return details;
}
}
+55 -8
View File
@@ -2,22 +2,69 @@ package dev.dao;
import dev.model.User;
public class UserDao {
import java.sql.*;
public boolean save(User user) {
public class UserDao
{
private final Connection connection;
// TODO:
// Insert user into database
public UserDao(Connection connection) {this.connection = connection;}
public boolean save(User user)
{
String sql = """
INSERT INTO users (username, password, email)
VALUES (?, ?, ?)
""";
try (PreparedStatement ps = connection.prepareStatement(sql))
{
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
int rowsAffected = ps.executeUpdate();
return rowsAffected > 0;
}
catch (SQLException e)
{
System.out.println("Error saving user: " + e.getMessage());
return false;
}
}
public User findByUsername(String username) {
public User findByUsername(String username)
{
String sql = """
SELECT id, username, password, email
FROM users
WHERE username = ?
""";
// TODO:
// Find a user by username
try (PreparedStatement ps = connection.prepareStatement(sql))
{
ps.setString(1, username);
try (ResultSet rs = ps.executeQuery())
{
if (rs.next())
{
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
return user;
}
}
}
catch (SQLException e) {System.out.println("Error finding user: " + e.getMessage());}
return null;
}
}
@@ -1,27 +1,26 @@
package dev.database;
import java.sql.Connection;
import java.sql.DriverManager;
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 = "postgres";
private static final String USER = "postgres"; // Your Username
private static final String PASSWORD = "Romina85";
private static final String PASSWORD = "password"; // Your Password
private DatabaseConnection() {}
private DatabaseConnection() {
public static Connection getConnection() throws SQLException
{
try {Class.forName("org.postgresql.Driver");}
catch (ClassNotFoundException e) {throw new RuntimeException("PostgreSQL Driver not found!", e);}
return DriverManager.getConnection(URL, USER, PASSWORD);
}
public static Connection getConnection()
throws SQLException {
// TODO:
// Return a valid PostgreSQL connection
return null;
}
}
+34 -6
View File
@@ -1,15 +1,43 @@
package dev.model;
public class MenuItem {
public class MenuItem
{
private int id;
private String name;
private String description;
private double price;
private String category;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getDescription() {return description;}
public void setDescription(String description) {this.description = description;}
public double getPrice() {return price;}
public void setPrice(double price) {this.price = price;}
public String getCategory() {return category;}
public void setCategory(String category) {this.category = category;}
@Override
public String toString()
{
return "MenuItem{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", price=" + price +
", category='" + category + '\'' +
'}';
}
}
+17 -5
View File
@@ -2,14 +2,26 @@ package dev.model;
import java.time.LocalDateTime;
public class Order {
public class Order
{
private int id;
private int userId;
private LocalDateTime createdAt;
private double totalPrice;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public int getUserId() {return userId;}
public void setUserId(int userId) {this.userId = userId;}
public LocalDateTime getCreatedAt() {return createdAt;}
public void setCreatedAt(LocalDateTime createdAt) {this.createdAt = createdAt;}
public double getTotalPrice() {return totalPrice;}
public void setTotalPrice(double totalPrice) {this.totalPrice = totalPrice;}
}
+21 -6
View File
@@ -1,15 +1,30 @@
package dev.model;
public class OrderDetail {
public class OrderDetail
{
private int id;
private int orderId;
private int menuItemId;
private int quantity;
private double price;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public int getOrderId() {return orderId;}
public void setOrderId(int orderId) {this.orderId = orderId;}
public int getMenuItemId() {return menuItemId;}
public void setMenuItemId(int menuItemId) {this.menuItemId = menuItemId;}
public int getQuantity() {return quantity;}
public void setQuantity(int quantity) {this.quantity = quantity;}
public double getPrice() {return price;}
public void setPrice(double price) {this.price = price;}
}
+17 -5
View File
@@ -1,13 +1,25 @@
package dev.model;
public class User {
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;}
}
+37 -7
View File
@@ -1,23 +1,53 @@
package dev.service;
import dev.dao.UserDao;
import dev.model.User;
public class AuthService {
public class AuthService
{
private final UserDao userDao;
public boolean register(String username, String password, String email) {
public AuthService(UserDao userDao) {this.userDao = userDao;}
// TODO:
// Validate and register user
public boolean register(String username, String password, String email)
{
if (username == null || username.isBlank()) return false;
if (password == null || password.length() < 4) return false;
if (userDao.findByUsername(username) != null)
{
System.out.println("Username already exists!");
return false;
}
public User login(String username, String password) {
User user = new User();
user.setUsername(username);
// TODO:
// Authenticate user
user.setPassword(password);
user.setEmail(email);
return userDao.save(user);
}
public User login(String username, String password)
{
if (username == null || password == null) return null;
User user = userDao.findByUsername(username);
if (user == null)
{
System.out.println("User not found!");
return null;
}
if (!user.getPassword().equals(password))
{
System.out.println("Wrong password!");
return null;
}
return user;
}
}
+33 -4
View File
@@ -1,12 +1,41 @@
package dev.service;
public class MenuService {
import dev.dao.MenuItemDao;
import dev.model.MenuItem;
public void showMenu() {
import java.util.List;
// TODO:
// Display menu items
public class MenuService
{
private final MenuItemDao menuItemDao;
public MenuService(MenuItemDao menuItemDao) {this.menuItemDao = menuItemDao;}
public void showMenu()
{
List<MenuItem> items = menuItemDao.findAll();
if (items == null || 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.getId() + ". " +
item.getName() + " - $" +
item.getPrice()
);
if (item.getDescription() != null) {System.out.println(" " + item.getDescription());}
}
System.out.println("=================================");
}
}
+137 -11
View File
@@ -1,26 +1,152 @@
package dev.service;
public class OrderService {
import dev.dao.MenuItemDao;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.model.MenuItem;
import dev.model.Order;
import dev.model.OrderDetail;
public void placeOrder(int userId) {
import java.time.LocalDateTime;
import java.util.List;
import java.util.Scanner;
// TODO:
// Create order
public class OrderService
{
private final OrderDao orderDao;
private final OrderDetailDao orderDetailDao;
private final MenuItemDao menuItemDao;
public OrderService(OrderDao orderDao,
OrderDetailDao orderDetailDao,
MenuItemDao menuItemDao) {
this.orderDao = orderDao;
this.orderDetailDao = orderDetailDao;
this.menuItemDao = menuItemDao;
}
public void printReceipt(int orderId) {
public void placeOrder(int userId)
{
Scanner scanner = new Scanner(System.in);
// TODO:
// Print order receipt
double totalPrice = 0;
Order order = new Order();
order.setUserId(userId);
order.setCreatedAt(LocalDateTime.now());
order.setTotalPrice(0);
int orderId = orderDao.save(order);
if (orderId == -1)
{
System.out.println("Failed to create order!");
return;
}
public void showOrderHistory(int userId) {
// TODO:
// Display user's order history
System.out.println("Available Menu:");
List<MenuItem> items = menuItemDao.findAll();
for (MenuItem item : items)
{
System.out.println(item.getId() + ". " +
item.getName() + " - $" +
item.getPrice());
}
while (true)
{
System.out.print("Enter item id (0 to finish): ");
int itemId = scanner.nextInt();
if (itemId == 0) break;
MenuItem menuItem = menuItemDao.findById(itemId);
if (menuItem == null)
{
System.out.println("Invalid item!");
continue;
}
System.out.print("Enter quantity: ");
int qty = scanner.nextInt();
double itemTotal = menuItem.getPrice() * qty;
totalPrice += itemTotal;
OrderDetail detail = new OrderDetail();
detail.setOrderId(orderId);
detail.setMenuItemId(itemId);
detail.setQuantity(qty);
detail.setPrice(menuItem.getPrice());
orderDetailDao.save(detail);
System.out.println("Added: " + qty + " x " + menuItem.getName());
}
System.out.println("=================================");
System.out.println("Final Total: $" + totalPrice);
System.out.println("Order placed successfully!");
}
public void printReceipt(int orderId)
{
List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
if (details.isEmpty())
{
System.out.println("No order found!");
return;
}
System.out.println("=================================");
System.out.println(" RECEIPT");
System.out.println("Order ID: " + orderId);
System.out.println("=================================");
System.out.println("Item\tQty\tPrice\tTotal");
double grandTotal = 0;
for (OrderDetail d : details)
{
MenuItem item = menuItemDao.findById(d.getMenuItemId());
double total = d.getQuantity() * d.getPrice();
grandTotal += total;
System.out.println(item.getName() + "\t"
+ d.getQuantity() + "\t"
+ d.getPrice() + "\t"
+ total);
}
System.out.println("=================================");
System.out.println("Grand Total: $" + grandTotal);
System.out.println("=================================");
}
public void showOrderHistory(int userId)
{
List<Order> orders = orderDao.findByUserId(userId);
if (orders.isEmpty())
{
System.out.println("No orders found.");
return;
}
System.out.println("=================================");
System.out.println(" ORDER HISTORY");
System.out.println("=================================");
for (Order order : orders)
{
System.out.println("Order ID: " + order.getId());
System.out.println("Date: " + order.getCreatedAt());
System.out.println("Total: $" + order.getTotalPrice());
System.out.println("---------------------------------");
}
}
}
+100 -18
View File
@@ -1,16 +1,34 @@
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 {
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;
public void start() {
private User loggedInUser;
while (true) {
public ConsoleMenu(AuthService authService,
MenuService menuService,
OrderService orderService) {
this.authService = authService;
this.menuService = menuService;
this.orderService = orderService;
}
public void start()
{
while (true)
{
System.out.println();
System.out.println("===== JAVA PIZZERIA =====");
System.out.println("1. Login");
@@ -18,27 +36,91 @@ public class ConsoleMenu {
System.out.println("3. Exit");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
switch (choice)
{
case 1 -> login();
case 1:
// TODO
break;
case 2 -> register();
case 2:
// TODO
break;
case 3:
case 3 ->
{
System.out.println("Goodbye!");
return;
default:
System.out.println("Invalid choice");
}
default -> System.out.println("Invalid choice");
}
}
}
private void login()
{
System.out.print("Username: ");
String username = scanner.nextLine();
System.out.print("Password: ");
String password = scanner.nextLine();
User user = authService.login(username, password);
if (user != null)
{
loggedInUser = user;
System.out.println("Login successful!");
userMenu();
}
else {System.out.println("Login failed!");}
}
private void register()
{
System.out.print("Username: ");
String username = scanner.nextLine();
System.out.print("Password: ");
String password = scanner.nextLine();
System.out.print("Email: ");
String email = scanner.nextLine();
boolean success = authService.register(username, password, email);
if (success) {System.out.println("Registration successful!");}
else {System.out.println("Registration failed!");}
}
private void userMenu()
{
while (true)
{
System.out.println();
System.out.println("===== MAIN MENU =====");
System.out.println("1. View Menu");
System.out.println("2. Place Order");
System.out.println("3. Order History");
System.out.println("4. Logout");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice)
{
case 1 -> menuService.showMenu();
case 2 -> orderService.placeOrder(loggedInUser.getId());
case 3 -> orderService.showOrderHistory(loggedInUser.getId());
case 4 ->
{
loggedInUser = null;
return;
}
default -> System.out.println("Invalid choice");
}
}
}
}