Compare commits

10 Commits
Author SHA1 Message Date
Fateme_Azizi dd6e81bcd5 update multiple classes 2026-06-27 21:12:42 +03:30
Fateme_Azizi 3573dc1f58 edit OrderDetailDao.java 2026-06-27 04:12:33 +03:30
Fateme_Azizi de2c9530c7 implement OrderService.java 2026-06-27 04:11:46 +03:30
Fateme_Azizi d26975c816 implement showMenu() 2026-06-27 04:11:10 +03:30
Fateme_Azizi 878ebcdc6c edit MenuItem.java 2026-06-27 02:50:44 +03:30
Fateme_Azizi 884e95957d implement AuthService.java 2026-06-27 02:25:12 +03:30
Fateme_Azizi d5f3f4f38f Add database connection implementation 2026-06-27 02:11:06 +03:30
Fateme_Azizi 62de8172ed implement UserDao.java 2026-06-27 01:54:38 +03:30
Fateme_Azizi 0bb90c8c62 implement User.java 2026-06-27 01:54:02 +03:30
Fateme_Azizi 8f1cf660db implement OrderDetailDao.java 2026-06-27 01:28:22 +03:30
18 changed files with 467 additions and 157 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>
+17
View File
@@ -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="f6d07e17-51cf-4ac6-b639-e1093cb323b7">
<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>
+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="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>
+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="21" project-jdk-type="JavaSDK" />
</project>
+6
View File
@@ -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
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>
+37 -132
View File
@@ -1,141 +1,46 @@
-- Restaurant Database Management System CREATE TABLE users (
-- id SERIAL PRIMARY KEY,
-- Instructions: username VARCHAR(20) NOT NULL UNIQUE,
-- 1. Create all required tables. password VARCHAR(20) NOT NULL,
-- 2. Design appropriate PRIMARY KEY and FOREIGN KEY relationships. email VARCHAR(100) UNIQUE
-- 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.
CREATE TABLE menu_items(
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL ,
description TEXT,
price NUMERIC(10, 2) NOT NULL CHECK ( price>0 ),
category VARCHAR(50)
);
-- ======================================================= CREATE TABLE orders(
-- USER TABLE id SERIAL PRIMARY KEY,
-- ======================================================= user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-- created_at TIMESTAMP NOT NULL,
-- Represents customers using the system. total_price NUMERIC(10, 2) NOT NULL CHECK (total_price >= 0)
--
-- 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 order_detail(
-- ======================================================= id SERIAL PRIMARY KEY,
-- MENU ITEM TABLE order_id INTEGER NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
-- ======================================================= menu_item_id INTEGER NOT NULL REFERENCES menu_items(id),
-- quantity INTEGER NOT NULL CHECK (quantity > 0),
-- Represents available food and drink items. price NUMERIC(10, 2) NOT NULL CHECK (price > 0)
-- );
-- 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 ...
INSERT INTO menu_items (name, description, price, category)
VALUES
('Margherita Classica', 'Tomato sauce, fresh mozzarella, and basil on a crispy thin crust', 16.00, 'Pizza'),
('Smoked BBQ Bacon Burger', 'Angus beef with cheddar, bacon, onion rings, and BBQ sauce on a brioche bun.', 14.50, 'Burger'),
('Truffle Mushroom Fettuccine', 'Creamy fettuccine with mushrooms, Parmesan, and a touch of truffle oil.', 18.00, 'Pasta'),
('Cola', 'Cold soft drink', 2.50, 'Drink');
-- =======================================================
-- ORDER TABLE
-- =======================================================
-- --
-- Represents orders placed by customers. SELECT * FROM users;
-- SELECT * FROM menu_items;
-- Required information: SELECT * FROM orders;
-- - Unique identifier SELECT * FROM order_detail;
-- - 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 ...
-- =======================================================
-- 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 ...
-- =======================================================
-- INITIAL MENU DATA
-- =======================================================
--
-- Insert at least 3 food or drink items.
--
-- Example categories:
-- - Pizza
-- - Burger
-- - Pasta
-- - Drink
--
-- INSERT INTO ...
-- =======================================================
-- OPTIONAL TEST DATA
-- =======================================================
--
-- You may insert sample users and orders for testing.
-- This section is optional.
--
-- INSERT INTO ...
-- =======================================================
-- VERIFICATION QUERIES
-- =======================================================
--
-- Uncomment these queries to verify your database.
--
-- SELECT * FROM ...;
-- SELECT * FROM ...;
-- SELECT * FROM ...;
-- SELECT * FROM ...;
+53 -3
View File
@@ -1,24 +1,74 @@
package dev.dao; package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.OrderDetail; 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; import java.util.List;
public class OrderDetailDao { public class OrderDetailDao {
public void save(OrderDetail detail) { public void save(OrderDetail detail) {
// TODO:
// Insert order detail // Insert order detail
String sql = "INSERT INTO order_detail (order_id, menu_item_id, quantity, price) VALUES(?, ?, ?, ?)";
try(Connection connection = DatabaseConnection.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setInt(1, detail.getOrderId());
preparedStatement.setInt(2, detail.getMenuItemId());
preparedStatement.setInt(3, detail.getQuantity());
preparedStatement.setDouble(4, detail.getPrice());
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
} }
public List<OrderDetail> findByOrderId(int orderId) { public List<OrderDetail> findByOrderId(int orderId) {
// TODO:
// Retrieve order details // Retrieve order details
return null; String sql = "SELECT * FROM order_detail WHERE order_id=?";
List<OrderDetail> orderDetails = new ArrayList<>();
try(Connection connection = DatabaseConnection.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setInt(1, orderId);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
OrderDetail orderDetail = new OrderDetail();
orderDetail.setId(resultSet.getInt("id"));
orderDetail.setOrderId(resultSet.getInt("order_id"));
orderDetail.setMenuItemId(resultSet.getInt("menu_item_id"));
orderDetail.setQuantity(resultSet.getInt("quantity"));
orderDetail.setPrice(resultSet.getDouble("price"));
orderDetails.add(orderDetail);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return orderDetails;
} }
} }
+44 -4
View File
@@ -1,23 +1,63 @@
package dev.dao; package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.User; import dev.model.User;
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:
// Insert user into database // Insert user into database
return false; String sql = "INSERT INTO users (username, password, email) VALUES(?, ?, ?)";
try(Connection connection = DatabaseConnection.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getEmail());
return preparedStatement.executeUpdate() > 0;
} catch (SQLException e) {
throw new RuntimeException(e);
}
} }
public User findByUsername(String username) { public User findByUsername(String username) {
// TODO:
// Find a user by username // Find a user by username
// Retrieve all orders of a user
String sql = "SELECT * FROM users WHERE username=?";
try (Connection connection = DatabaseConnection.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, username);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
return user;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
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"; // DB Server private static final String URL = "jdbc:postgresql://localhost:5432/postgres"; // DB Server
private static final String USER = "postgres"; // Your Username private static final String USER = "postgres"; // Your Username
private static final String PASSWORD = "password"; // Your Password private static final String PASSWORD = "1234"; // Your Password
private DatabaseConnection() { private DatabaseConnection() {
@@ -18,10 +19,8 @@ public class DatabaseConnection {
public static Connection getConnection() public static Connection getConnection()
throws SQLException { throws SQLException {
// TODO:
// Return a valid PostgreSQL connection // Return a valid PostgreSQL connection
return DriverManager.getConnection(URL, USER, PASSWORD);
return null;
} }
} }
+6
View File
@@ -17,4 +17,10 @@ public class MenuItem {
public void setDescription(String description) { this.description = description; } public void setDescription(String description) { this.description = description; }
public void setPrice(double price) { this.price = price; } public void setPrice(double price) { this.price = price; }
public void setCategory(String category) { this.category = category; } public void setCategory(String category) { this.category = category; }
public int getId() { return id; }
public String getName() { return name; }
public String getDescription() { return description; }
public double getPrice() { return price; }
public String getCategory() { return category; }
} }
+11
View File
@@ -10,4 +10,15 @@ public class User {
private String email; private String email;
public void setId(int id) { this.id = id; }
public void setUsername(String username) { this.username= username; }
public void setPassword(String password) { this.password = password; }
public void setEmail(String email) { this.email = email; }
public int getId() { return id; }
public String getUsername() { return username; }
public String getEmail() { return email; }
public String getPassword() { return password; }
} }
+19 -2
View File
@@ -1,22 +1,39 @@
package dev.service; package dev.service;
import dev.dao.UserDao;
import dev.model.User; import dev.model.User;
public class AuthService { public class AuthService {
UserDao userDao = new UserDao();
public boolean register(String username, String password, String email) { public boolean register(String username, String password, String email) {
// TODO:
// Validate and register user // Validate and register user
if( username == null || username.isBlank() || password == null || password.isBlank())
return false;
if (userDao.findByUsername(username) == null) {
User user = new User();
user.setEmail(email);
user.setPassword(password);
user.setUsername(username);
return userDao.save(user);
}
return false; return false;
} }
public User login(String username, String password) { public User login(String username, String password) {
// TODO:
// Authenticate user // Authenticate user
User user = userDao.findByUsername(username);
if (user != null && user.getPassword().equals(password)) {
return user;
}
return null; return null;
} }
+15 -2
View File
@@ -1,12 +1,25 @@
package dev.service; package dev.service;
import dev.dao.MenuItemDao;
import dev.model.MenuItem;
import java.util.List;
public class MenuService { public class MenuService {
public void showMenu() { public void showMenu() {
// TODO:
// Display menu items // Display menu items
MenuItemDao menuItemDao = new MenuItemDao();
List<MenuItem> items = menuItemDao.findAll();
for ( MenuItem menuItem : items) {
System.out.println(menuItem.getId() + ". " + menuItem.getName() +
" " + menuItem.getPrice() + "$ \n" +
menuItem.getCategory() + " | " + menuItem.getDescription());
System.out.println();
}
} }
} }
+98 -4
View File
@@ -1,25 +1,119 @@
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.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class OrderService { public class OrderService {
MenuItemDao menuItemDao = new MenuItemDao();
OrderDetailDao orderDetailDao = new OrderDetailDao();
OrderDao orderDao = new OrderDao();
Scanner in = new Scanner(System.in);
public void placeOrder(int userId) { public void placeOrder(int userId) {
// TODO: List<OrderDetail> details = new ArrayList<>();
// Create order int totalPrice = 0;
// Create order
while (true) {
System.out.println("Enter the id of your order (-1 to exit) : ");
int id = in.nextInt();
if(id==-1) break;
MenuItem menuItem = menuItemDao.findById(id);
if(menuItem != null) {
System.out.println("Enter quantity: ");
int quantity = in.nextInt();
if(quantity<=0) {
System.out.println("Quantity can't be negative");
continue;
}
OrderDetail orderDetail = new OrderDetail();
orderDetail.setPrice(menuItem.getPrice());
orderDetail.setQuantity(quantity);
orderDetail.setMenuItemId(id);
details.add(orderDetail);
totalPrice += menuItem.getPrice()*quantity;
System.out.println(quantity+ " " + menuItem.getName() + "(s) got added to your order.");
}
}
if (totalPrice<=0) return;
Order order = new Order();
order.setTotalPrice(totalPrice);
order.setUserId(userId);
int orderId = orderDao.save(order);
if (orderId == -1) {
System.out.println("Order could not be saved");
return;
}
for(OrderDetail orderDetail : details) {
orderDetail.setOrderId(orderId);
orderDetailDao.save(orderDetail);
}
printReceipt(orderId);
} }
public void printReceipt(int orderId) { public void printReceipt(int orderId) {
// TODO:
// Print order receipt // Print order receipt
List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
if (details.isEmpty()) return;
double totalPrice = 0;
System.out.println("\n============ RECEIPT ============");
for (OrderDetail detail : details) {
MenuItem item = menuItemDao.findById(detail.getMenuItemId());
double subtotal = detail.getPrice() * detail.getQuantity();
totalPrice += subtotal;
System.out.println( item.getName() + " | Quantity: " + detail.getQuantity() +
" | Price: " + detail.getPrice() + "$ | Total: " + subtotal + "$");
}
System.out.println("==============================");
System.out.println("Final Total: $" + totalPrice);
} }
public void showOrderHistory(int userId) { public void showOrderHistory(int userId) {
// TODO:
// Display user's order history // Display user's order history
List<Order> orders = orderDao.findByUserId(userId);
if (orders.isEmpty()) return;
System.out.println("\n===== ORDER HISTORY =====");
for (Order order : orders) {
System.out.println( "Order #" + order.getId() + " | Date: " + order.getCreatedAt() +
" | Total: " + order.getTotalPrice() + "$");
}
} }
+88 -4
View File
@@ -1,12 +1,21 @@
package dev.ui; package dev.ui;
import dev.model.User;
import dev.service.AuthService;
import dev.service.MenuService;
import dev.service.OrderService;
import java.util.Scanner; import java.util.Scanner;
public class ConsoleMenu { public class ConsoleMenu {
private final Scanner scanner = private final Scanner in =
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) {
@@ -17,16 +26,17 @@ public class ConsoleMenu {
System.out.println("2. Register"); System.out.println("2. Register");
System.out.println("3. Exit"); System.out.println("3. Exit");
int choice = scanner.nextInt(); int choice = in.nextInt();
in.nextLine();
switch (choice) { switch (choice) {
case 1: case 1:
// TODO login();
break; break;
case 2: case 2:
// TODO register();
break; break;
case 3: case 3:
@@ -41,4 +51,78 @@ public class ConsoleMenu {
} }
public void login() {
System.out.println("Enter your username: ");
String username = in.nextLine();
System.out.println("Enter your password: ");
String password = in.nextLine();
User user = authService.login(username, password);
if(user != null) {
System.out.println("Welcome back, " + username);
showOptions(user);
}
else System.out.println("Wrong username or password.");
}
public void register() {
System.out.println("Enter your username: ");
String username = in.nextLine();
System.out.println("Enter password: ");
String password = in.nextLine();
System.out.println("Enter your email: ");
String email = in.nextLine();
if (authService.register(username, password, email)) {
System.out.println("Welcome!");
}
else System.out.println("Registration failed");
}
public void showOptions(User user) {
System.out.println("""
=======================================
\uD83C\uDF7D MAIN MENU \uD83C\uDF7D
=======================================""");
while (true) {
System.out.println("1. View Menu\n" +
"2. Place a New Order\n" +
"3. View Order History \n" +
"4. Logout");
int choice = in.nextInt();
switch (choice) {
case 1:
menuService.showMenu();
break;
case 2:
orderService.placeOrder(user.getId());
break;
case 3:
orderService.showOrderHistory(user.getId());
break;
case 4:
return;
}
}
}
} }