Updated MenuItem and User, and completed AuthService, MenuService, OrderService and ConsoleMenu.
This commit is contained in:
@@ -19,4 +19,24 @@ public class MenuItem {
|
||||
this.price = price;
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return this.description;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return this.price;
|
||||
}
|
||||
|
||||
public String getCategory() {
|
||||
return this.category;
|
||||
}
|
||||
}
|
||||
@@ -10,4 +10,18 @@ public class User {
|
||||
|
||||
private String email;
|
||||
|
||||
public User(int id, String username, String password, String email) {
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return this.username;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,75 @@
|
||||
package dev.service;
|
||||
|
||||
import dev.database.DatabaseConnection;
|
||||
import dev.model.User;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.sql.*;
|
||||
import java.util.Base64;
|
||||
|
||||
public class AuthService {
|
||||
|
||||
private String hashPassword(String password) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hash = digest.digest(password.getBytes("UTF-8"));
|
||||
return Base64.getEncoder().encodeToString(hash);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Hashing failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean register(String username, String password, String email) {
|
||||
|
||||
// TODO:
|
||||
// Validate and register user
|
||||
|
||||
if (username == null || username.trim().isEmpty() || password == null || password.isEmpty()) {
|
||||
System.out.println("Username and password cannot be empty.");
|
||||
return false;
|
||||
}
|
||||
|
||||
String sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement pstmt = conn.prepareStatement(sql)) {
|
||||
|
||||
pstmt.setString(1, username);
|
||||
pstmt.setString(2, hashPassword(password));
|
||||
if (email == null || email.trim().isEmpty()) {
|
||||
pstmt.setNull(3, Types.VARCHAR);
|
||||
} else {
|
||||
pstmt.setString(3, email);
|
||||
}
|
||||
|
||||
pstmt.executeUpdate();
|
||||
return true;
|
||||
} catch (SQLException e) {
|
||||
System.out.println("Registration failed (Username might already exist): " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public User login(String username, String password) {
|
||||
|
||||
// TODO:
|
||||
// Authenticate user
|
||||
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement pstmt = conn.prepareStatement(sql)) {
|
||||
|
||||
pstmt.setString(1, username);
|
||||
pstmt.setString(2, hashPassword(password));
|
||||
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
return new User(
|
||||
rs.getInt("id"),
|
||||
rs.getString("username"),
|
||||
rs.getString("password"),
|
||||
rs.getString("email")
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.out.println("Login error: " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +1,27 @@
|
||||
package dev.service;
|
||||
|
||||
import dev.dao.MenuItemDao;
|
||||
import dev.model.MenuItem;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class MenuService {
|
||||
|
||||
public void showMenu() {
|
||||
final MenuItemDao menuItemDao = new MenuItemDao();
|
||||
|
||||
// TODO:
|
||||
// Display menu items
|
||||
|
||||
List<MenuItem> items = menuItemDao.findAll();
|
||||
if (items.isEmpty()) {
|
||||
System.out.println("The menu is currently empty.");
|
||||
return;
|
||||
}
|
||||
System.out.println("\n===== MENU =====");
|
||||
for (MenuItem item : items) {
|
||||
System.out.printf("[%d] %s - $%.2f (%s)\n", item.getId(), item.getName(), item.getPrice(), item.getCategory());
|
||||
if (item.getDescription() != null) {
|
||||
System.out.println(" " + item.getDescription());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +1,158 @@
|
||||
package dev.service;
|
||||
|
||||
import dev.dao.MenuItemDao;
|
||||
import dev.database.DatabaseConnection;
|
||||
import dev.model.MenuItem;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class OrderService {
|
||||
private final MenuItemDao menuItemDao = new MenuItemDao();
|
||||
private final Scanner scanner = new Scanner(System.in);
|
||||
|
||||
public void placeOrder(int userId) {
|
||||
Connection conn = null;
|
||||
try {
|
||||
conn = DatabaseConnection.getConnection();
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
// TODO:
|
||||
// Create order
|
||||
String insertOrderSql = "INSERT INTO orders (user_id, total_price) VALUES (?, 0.00)";
|
||||
PreparedStatement orderStmt = conn.prepareStatement(insertOrderSql, Statement.RETURN_GENERATED_KEYS);
|
||||
orderStmt.setInt(1, userId);
|
||||
orderStmt.executeUpdate();
|
||||
|
||||
ResultSet generatedKeys = orderStmt.getGeneratedKeys();
|
||||
int orderId = 0;
|
||||
if (generatedKeys.next()) {
|
||||
orderId = generatedKeys.getInt(1);
|
||||
}
|
||||
|
||||
double grandTotal = 0.0;
|
||||
boolean addingItems = true;
|
||||
String insertDetailSql = "INSERT INTO order_details (order_id, menu_item_id, quantity, price_at_purchase) VALUES (?, ?, ?, ?)";
|
||||
PreparedStatement detailStmt = conn.prepareStatement(insertDetailSql);
|
||||
|
||||
while (addingItems) {
|
||||
System.out.print("Enter Menu Item ID to add (or 0 to finish): ");
|
||||
int itemId = scanner.nextInt();
|
||||
if (itemId == 0) {
|
||||
addingItems = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
MenuItem item = menuItemDao.findById(itemId);
|
||||
if (item == null) {
|
||||
System.out.println("Invalid Item ID. Try again.");
|
||||
continue;
|
||||
}
|
||||
|
||||
System.out.print("Enter quantity: ");
|
||||
int quantity = scanner.nextInt();
|
||||
if (quantity <= 0) {
|
||||
System.out.println("Quantity must be greater than zero.");
|
||||
continue;
|
||||
}
|
||||
|
||||
double subtotal = (item.getPrice()) * quantity;
|
||||
grandTotal += subtotal;
|
||||
|
||||
detailStmt.setInt(1, orderId);
|
||||
detailStmt.setInt(2, item.getId());
|
||||
detailStmt.setInt(3, quantity);
|
||||
detailStmt.setDouble(4, item.getPrice());
|
||||
detailStmt.executeUpdate();
|
||||
}
|
||||
|
||||
if (grandTotal == 0.0) {
|
||||
System.out.println("No items selected. Canceling order.");
|
||||
conn.rollback();
|
||||
return;
|
||||
}
|
||||
|
||||
String updateOrderSql = "UPDATE orders SET total_price = ? WHERE id = ?";
|
||||
PreparedStatement updateStmt = conn.prepareStatement(updateOrderSql);
|
||||
updateStmt.setDouble(1, grandTotal);
|
||||
updateStmt.setInt(2, orderId);
|
||||
updateStmt.executeUpdate();
|
||||
|
||||
conn.commit();
|
||||
System.out.println("Order successfully saved!");
|
||||
printReceipt(orderId);
|
||||
|
||||
} catch (SQLException e) {
|
||||
System.out.println("Order failed: " + e.getMessage());
|
||||
if (conn != null) {
|
||||
try { conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void printReceipt(int orderId) {
|
||||
|
||||
// TODO:
|
||||
// Print order receipt
|
||||
String sql = "SELECT od.quantity, od.price_at_purchase, m.name, o.total_price " +
|
||||
"FROM order_details od " +
|
||||
"JOIN menu_items m ON od.menu_item_id = m.id " +
|
||||
"JOIN orders o ON od.order_id = o.id " +
|
||||
"WHERE od.order_id = ?";
|
||||
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement pstmt = conn.prepareStatement(sql)) {
|
||||
|
||||
pstmt.setInt(1, orderId);
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
System.out.println("\n========= RECEIPT (Order #" + orderId + ") =========");
|
||||
double grandTotal = 0.0;
|
||||
boolean hasRows = false;
|
||||
|
||||
while (rs.next()) {
|
||||
hasRows = true;
|
||||
String name = rs.getString("name");
|
||||
int qty = rs.getInt("quantity");
|
||||
double price = rs.getDouble("price_at_purchase");
|
||||
double subtotal = qty * price;
|
||||
grandTotal = rs.getDouble("total_price");
|
||||
|
||||
System.out.printf("- %s x%d @ $%.2f = $%.2f\n", name, qty, price, subtotal);
|
||||
}
|
||||
if (!hasRows) {
|
||||
System.out.println("Order not found.");
|
||||
return;
|
||||
}
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.printf("GRAND TOTAL: $%.2f\n", grandTotal);
|
||||
System.out.println("========================================");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.out.println("Error generating receipt: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void showOrderHistory(int userId) {
|
||||
String sql = "SELECT id, created_at, total_price FROM orders WHERE user_id = ? ORDER BY created_at DESC";
|
||||
|
||||
// TODO:
|
||||
// Display user's order history
|
||||
try (Connection conn = DatabaseConnection.getConnection();
|
||||
PreparedStatement pstmt = conn.prepareStatement(sql)) {
|
||||
|
||||
pstmt.setInt(1, userId);
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
System.out.println("\n===== YOUR ORDER HISTORY =====");
|
||||
boolean hasHistory = false;
|
||||
while (rs.next()) {
|
||||
hasHistory = true;
|
||||
System.out.printf("Order #%d | Date: %s | Total Spent: $%.2f\n",
|
||||
rs.getInt("id"),
|
||||
rs.getTimestamp("created_at").toString(),
|
||||
rs.getDouble("total_price")
|
||||
);
|
||||
}
|
||||
if (!hasHistory) {
|
||||
System.out.println("You haven't placed any orders yet.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.out.println("Error fetching history: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +1,20 @@
|
||||
package dev.ui;
|
||||
|
||||
import dev.model.MenuItem;
|
||||
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 AuthService authService = new AuthService();
|
||||
private final MenuService menuService = new MenuService();
|
||||
private final OrderService orderService = new OrderService();
|
||||
|
||||
public void start() {
|
||||
|
||||
@@ -22,11 +31,11 @@ public class ConsoleMenu {
|
||||
switch (choice) {
|
||||
|
||||
case 1:
|
||||
// TODO
|
||||
handleLogin();
|
||||
break;
|
||||
|
||||
case 2:
|
||||
// TODO
|
||||
handleRegister();
|
||||
break;
|
||||
|
||||
case 3:
|
||||
@@ -41,4 +50,64 @@ public class ConsoleMenu {
|
||||
|
||||
}
|
||||
|
||||
private void handleRegister() {
|
||||
System.out.print("Choose Username: ");
|
||||
String user = scanner.nextLine();
|
||||
System.out.print("Choose Password: ");
|
||||
String pass = scanner.nextLine();
|
||||
System.out.print("Email (Optional, press Enter to skip): ");
|
||||
String email = scanner.nextLine();
|
||||
|
||||
if (authService.register(user, pass, email)) {
|
||||
System.out.println("Registration successful! You can now log in.");
|
||||
}
|
||||
}
|
||||
|
||||
private void handleLogin() {
|
||||
System.out.print("Username: ");
|
||||
String user = scanner.nextLine();
|
||||
System.out.print("Password: ");
|
||||
String pass = scanner.nextLine();
|
||||
|
||||
User loggedInUser = authService.login(user, pass);
|
||||
if (loggedInUser != null) {
|
||||
System.out.println("Welcome back, " + loggedInUser.getUsername() + "!");
|
||||
showCustomerDashboard(loggedInUser);
|
||||
} else {
|
||||
System.out.println("Invalid username or password.");
|
||||
}
|
||||
}
|
||||
|
||||
private void showCustomerDashboard(User user) {
|
||||
while (true) {
|
||||
System.out.println("\n===== CUSTOMER MENU =====");
|
||||
System.out.println("1. Browse Menu");
|
||||
System.out.println("2. Place 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:
|
||||
menuService.showMenu();
|
||||
orderService.placeOrder(user.getId());
|
||||
break;
|
||||
case 3:
|
||||
orderService.showOrderHistory(user.getId());
|
||||
break;
|
||||
case 4:
|
||||
System.out.println("Logged out successfully.");
|
||||
return;
|
||||
default:
|
||||
System.out.println("Invalid choice.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user