Complete assignment #1

Merged
peyman merged 1 commits from develop into main 2026-07-23 19:46:44 +00:00
23 changed files with 732 additions and 164 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="restaurant_db" uuid="58cfe2c8-dec0-4953-b2b5-821b6e7313f9">
<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>
+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="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://maven.myket.ir/" />
</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>
+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="PostgreSQL" />
</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>
+45 -105
View File
@@ -1,141 +1,81 @@
-- 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) UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
email VARCHAR(255) UNIQUE
);
-- =======================================================
-- 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(
id SERIAL PRIMARY KEY,
name VARCHAR(250) NOT NULL,
description TEXT,
price NUMERIC NOT NULL CHECK (price > 0),
category VARCHAR(50)
);
-- =======================================================
-- ORDER TABLE
-- =======================================================
--
-- Represents orders placed by customers.
--
-- Required information:
-- - Unique identifier
-- - Reference to customer
-- - Creation date and time
-- - Total price
--
-- Requirements:
-- - Each order must belong to exactly one user.
-- - A user can have multiple orders.
-- - The relationship between User and Order must be implemented.
--
-- Note:
-- Avoid using reserved SQL keywords as table names.
-- Consider using a name such as "orders" or "customer_orders".
--
-- CREATE TABLE ...
CREATE TABLE orders(
id SERIAL PRIMARY KEY,
user_id INT NOT NULL,
created_at TIMESTAMP NOT NULL ,
total_price NUMERIC NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- =======================================================
-- 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_id INT NOT NULL ,
quantity NUMERIC NOT NULL CHECK (quantity > 0),
item_price NUMERIC NOT NULL,
FOREIGN KEY (order_id) REFERENCES orders(id),
FOREIGN KEY (menu_id) REFERENCES menu(id)
);
-- =======================================================
-- INITIAL MENU DATA
-- =======================================================
--
-- Insert at least 3 food or drink items.
--
-- Example categories:
-- - Pizza
-- - Burger
-- - Pasta
-- - Drink
--
-- INSERT INTO ...
-- id is left out because it has SERIAl type and auto-generates.
INSERT INTO menu (name, description, price, category) VALUES
('Margherita Pizza', 'Classic tomato, mozzarella, and basil', 9.99, 'Pizza'),
('Grilled Chicken Wrap', 'Chicken, lettuce, tomato, garlic sauce', 7.49, 'Wraps'),
('Caesar Salad', 'Romaine, parmesan, croutons, caesar dressing', 6.99, 'Salads'),
('Beef Burger', 'Beef patty, cheddar, lettuce, brioche bun', 8.99, 'Burgers'),
('Spaghetti Carbonara', 'Pasta, egg, pancetta, parmesan', 10.49, 'Pasta'),
('Veggie Spring Rolls', 'Crispy rolls with mixed vegetables', 5.49, 'Appetizers'),
('Chocolate Lava Cake', 'Warm cake with molten chocolate center', 4.99, 'Dessert'),
('Iced Latte', 'Espresso with cold milk over ice', 3.49, 'Beverages'),
('Mushroom Risotto', 'Creamy arborio rice with wild mushrooms', 9.49, 'Pasta'),
('Fish Tacos', 'Grilled fish, cabbage slaw, chipotle mayo', 8.49, 'Tacos');
-- =======================================================
-- 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 ...;
-- SELECT * FROM users;
-- SELECT * FROM menu;
-- SELECT * FROM orders;
-- SELECT * FROM order_details;
+54 -6
View File
@@ -1,25 +1,73 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.MenuItem;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MenuItemDao {
public List<MenuItem> findAll() {
// TODO:
// Retrieve all menu items
String sql = "SELECT * FROM menu";
List<MenuItem> result = new ArrayList<>();
return null;
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
ResultSet rs = st.executeQuery();
while(rs.next()){
result.add(new MenuItem(
rs.getInt("id"),
rs.getString("name"),
rs.getString("description"),
rs.getDouble("price"),
rs.getString("category")
));
}
st.close();
} catch (SQLException e) {
System.err.println("Failed to fetch menu " + e.getMessage());
}
return result;
}
public MenuItem findById(int id) {
// TODO:
// Find menu item by id
String sql = "SELECT * FROM menu WHERE id=?";
MenuItem itemMenu = null;
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1, id);
ResultSet rs = st.executeQuery();
if(rs.next()){
itemMenu = new MenuItem(
rs.getInt("id"),
rs.getString("name"),
rs.getString("description"),
rs.getDouble("price"),
rs.getString("category")
);
}
st.close();
} catch (SQLException e) {
System.err.println("Failed to fetch item " + e.getMessage());
}
return itemMenu;
return null;
}
}
+53 -5
View File
@@ -1,25 +1,73 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.Order;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
public class OrderDao {
public int save(Order order) {
// TODO:
// Insert order and return generated id
String sql = "INSERT INTO orders(user_id, created_at, total_price) VALUES(?, ?, ?)";
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1, order.getUserId());
st.setTimestamp(2, Timestamp.valueOf(order.getCreatedAt()));
st.setDouble(3, order.getTotalPrice());
st.executeUpdate();
ResultSet rsKeys = st.getGeneratedKeys();
if(rsKeys.next()){
int orderId = rsKeys.getInt(1);
order.setId(orderId);
return orderId;
}
st.close();
} catch (SQLException e) {
System.err.println("Failed to add order " + e.getMessage());
}
return -1;
}
public List<Order> findByUserId(int userId) {
// TODO:
// Retrieve all orders of a user
String sql = "SELECT * FROM orders WHERE user_id=?";
List<Order> result = new ArrayList<>();
try {
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1,userId);
ResultSet rs = st.executeQuery();
while (rs.next()){
result.add(new Order(
rs.getInt("id"),
rs.getInt("user_id"),
rs.getTimestamp("created_at").toLocalDateTime(),
rs.getInt("total_price")
));
}
st.close();
} catch (SQLException e) {
System.err.println("Unable to find user: " + e.getMessage());
}
return result;
return null;
}
}
+47 -5
View File
@@ -1,24 +1,66 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.OrderDetail;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class OrderDetailDao {
public void save(OrderDetail detail) {
// TODO:
// Insert order detail
String sql = "INSERT INTO order_details (order_id, menu_id, quantity, item_price) VALUES (?,?,?,?)";
try {
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1, detail.getOrderId());
st.setInt(2, detail.getMenuItemId());
st.setInt(3, detail.getQuantity());
st.setDouble(4, detail.getPrice());
st.executeUpdate();
st.close();
} catch (SQLException e) {
System.err.println("Error writing order details: " + e.getMessage());
}
}
public List<OrderDetail> findByOrderId(int orderId) {
// TODO:
// Retrieve order details
List<OrderDetail> result = new ArrayList<>();
return null;
String sql = "SELECT * FROM order_details WHERE order_id=?";
try {
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setInt(1,orderId);
ResultSet rs = st.executeQuery();
while (rs.next()){
result.add(new OrderDetail(
rs.getInt("id"),
rs.getInt("order_id"),
rs.getInt("menu_id"),
rs.getInt("quantity"),
rs.getDouble("item_price")
)
);
}
st.close();
} catch (SQLException e) {
System.err.println("Error retrieving order details: " + e.getMessage());
}
return result;
}
}
+45 -5
View File
@@ -1,23 +1,63 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
public boolean save(User user) {
// TODO:
// Insert user into database
String sql = "INSERT INTO users (username, password_hash, email) VALUES (?, ?, ?)";
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setString(1, user.getUsername());
st.setString(2, user.getPassword());
st.setString(3, user.getEmail());
st.executeUpdate();
st.close();
return true;
} catch (SQLException e) {
System.err.println("Failed to save user " + e.getMessage());
}
return false;
}
public User findByUsername(String username) {
// TODO:
// Find a user by username
String sql = "SELECT * FROM users WHERE username=?";
User result = null;
try{
PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
st.setString(1, username);
ResultSet rs = st.executeQuery();
if(rs.next()){
result = new User(
rs.getInt("id"),
rs.getString("username"),
rs.getString("password_hash"),
rs.getString("email")
);
}
st.close();
} catch (SQLException e) {
System.err.println("Failed to fild user " + e.getMessage());
}
return result;
return null;
}
}
@@ -1,15 +1,16 @@
package dev.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:postgresql://localhost:5432/restaurant_db"; // DB Server
private static final String USER = "postgres"; // Your Username
private static final String USER = "matin"; // Your Username
private static final String PASSWORD = "password"; // Your Password
private static final String PASSWORD = "0000"; // Your Password
private DatabaseConnection() {
@@ -18,10 +19,8 @@ public class DatabaseConnection {
public static Connection getConnection()
throws SQLException {
// TODO:
// Return a valid PostgreSQL connection
return DriverManager.getConnection(URL, USER, PASSWORD);
return null;
}
}
+38 -4
View File
@@ -3,13 +3,47 @@ package dev.model;
public class MenuItem {
private int id;
private String name;
private String description;
private double price;
private String category;
public MenuItem(int id, String name, String description, double price, String category) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
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;
}
@Override
public String toString() {
return "MenuItem{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", price=" + price +
", category='" + category + '\'' +
'}';
}
}
+54 -3
View File
@@ -5,11 +5,62 @@ import java.time.LocalDateTime;
public class Order {
private int id;
private int userId;
private LocalDateTime createdAt;
private int totalPrice;
private double totalPrice;
public Order(int id, int totalPrice, LocalDateTime createdAt, int userId) {
this.id = id;
this.totalPrice = totalPrice;
this.createdAt = createdAt;
this.userId = userId;
}
public Order(int userId, LocalDateTime createdAt, int totalPrice) {
this.userId = userId;
this.createdAt = createdAt;
this.totalPrice = totalPrice;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", userId=" + userId +
", createdAt=" + createdAt +
", totalPrice=" + totalPrice +
'}';
}
}
+65 -4
View File
@@ -3,13 +3,74 @@ package dev.model;
public class OrderDetail {
private int id;
private int orderId;
private int menuItemId;
private int quantity;
private double price;
public OrderDetail(int id, int orderId, int menuItemId, int quantity, double price) {
this.id = id;
this.orderId = orderId;
this.menuItemId = menuItemId;
this.quantity = quantity;
this.price = price;
}
public OrderDetail(int orderId, int menuItemId, int quantity, double price) {
this.orderId = orderId;
this.menuItemId = menuItemId;
this.quantity = quantity;
this.price = price;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getMenuItemId() {
return menuItemId;
}
public void setMenuItemId(int menuItemId) {
this.menuItemId = menuItemId;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "OrderDetail{" +
"id=" + id +
", orderId=" + orderId +
", menuItemId=" + menuItemId +
", quantity=" + quantity +
", price=" + price +
'}';
}
}
+34 -3
View File
@@ -3,11 +3,42 @@ package dev.model;
public class User {
private int id;
private String username;
private String password;
private String email;
// verify user for the first time
public User(int id, String username, String password, String email){
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
// verified user
public User(String username, String password, String email){
this.username = username;
this.password = password;
this.email = email;
}
public void setId(int id){
this.id = id;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getEmail() {
return email;
}
}
+23 -4
View File
@@ -1,21 +1,40 @@
package dev.service;
import dev.dao.UserDao;
import dev.model.User;
import java.util.Objects;
public class AuthService {
private final UserDao userDao = new UserDao();
public boolean register(String username, String password, String email) {
// TODO:
// Validate and register user
User user = new User(
username,
String.valueOf(password.hashCode()),
email
);
if(userDao.save(user)){
System.out.println("Registered successfully");
return true;
}
return false;
}
public User login(String username, String password) {
// TODO:
// Authenticate user
User userDB = userDao.findByUsername(username);
if(userDB == null) return null;
String userPasswordDB = userDB.getPassword();
if( Objects.equals( userPasswordDB, String.valueOf(password.hashCode()) ) )
return userDB;
return null;
}
+11 -2
View File
@@ -1,11 +1,20 @@
package dev.service;
import dev.dao.MenuItemDao;
import dev.model.MenuItem;
import java.util.List;
public class MenuService {
public static final MenuItemDao menuItemDao = new MenuItemDao();
public void showMenu() {
// TODO:
// Display menu items
List<MenuItem> items = menuItemDao.findAll();
for(MenuItem item : items){
System.out.println(item);
}
}
+122 -6
View File
@@ -1,25 +1,141 @@
package dev.service;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.model.MenuItem;
import dev.model.Order;
import dev.model.OrderDetail;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
public class OrderService {
private final static OrderDetailDao orderDetailDao = new OrderDetailDao();
private final static OrderDao orderDao = new OrderDao();
private final static MenuService menuService = new MenuService();
private final static Scanner scanner = new Scanner(System.in);
public void placeOrder(int userId) {
// TODO:
// Create order
List<MenuItem> menuItems = MenuService.menuItemDao.findAll();
if (menuItems.isEmpty()) {
System.out.println("No menu items available.");
return;
}
// Display menu
System.out.println("========== MENU ==========");
for (MenuItem item : menuItems) {
System.out.printf("%-4d %-25s %10.2f%n",
item.getId(), item.getName(), item.getPrice());
}
System.out.println("===========================");
Order order = new Order(userId, LocalDateTime.now(), 0);
int orderId = orderDao.save(order);
double totalPrice = 0;
boolean addingItems = true;
while (addingItems) {
System.out.print("Enter menu item id to add (0 to finish): ");
int menuId = Integer.parseInt(scanner.nextLine().trim());
if (menuId == 0) {
addingItems = false;
continue;
}
MenuItem selected = MenuService.menuItemDao.findById(menuId);
if (selected == null) {
System.out.println("Invalid item id, try again.");
continue;
}
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(scanner.nextLine().trim());
if (quantity <= 0) {
System.out.println("Quantity must be positive.");
continue;
}
OrderDetail detail = new OrderDetail(
orderId,
selected.getId(),
quantity,
selected.getPrice()
);
orderDetailDao.save(detail);
totalPrice += selected.getPrice() * quantity;
System.out.println(selected.getName() + " x" + quantity + " added.");
}
if (totalPrice == 0) {
System.out.println("No items were added. Order canceled.");
return;
}
order.setId(orderId);
order.setTotalPrice((int) totalPrice);
orderDao.save(order);
System.out.println("Order placed successfully. Order ID: " + orderId);
printReceipt(orderId);
}
public void printReceipt(int orderId) {
// TODO:
// Print order receipt
List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
if(details.isEmpty())
return;
System.out.println("Order ID: " + orderId);
double total = 0;
for (OrderDetail detail : details) {
double subtotal = detail.getPrice() * detail.getQuantity();
total += subtotal;
System.out.printf("%-20s %dx $%.2f%n",
MenuService.menuItemDao.findById(detail.getMenuItemId()).getName(),
detail.getQuantity(),
subtotal
);
}
System.out.println("---------------------------");
System.out.printf("Total: $%.2f%n", total);
System.out.println("===========================\n");
}
public void showOrderHistory(int userId) {
// TODO:
// Display user's order history
List<Order> orders = orderDao.findByUserId(userId);
if (orders.isEmpty()){
System.err.println("No orders found.");
return;
}
for (Order order : orders){
System.out.println("Order ID: " + order.getId());
System.out.println("Date: " + order.getCreatedAt());
System.out.printf("Total: $%.2f%n", order.getTotalPrice());
System.out.println("---------------------------------");
printReceipt(order.getId());
}
}
+40 -7
View File
@@ -1,11 +1,15 @@
package dev.ui;
import dev.model.User;
import dev.service.AuthService;
import dev.service.MenuService;
import java.util.Scanner;
public class ConsoleMenu {
private final Scanner scanner =
new Scanner(System.in);
private final Scanner scanner = new Scanner(System.in);
private final AuthService authService = new AuthService();
public void start() {
@@ -21,13 +25,42 @@ public class ConsoleMenu {
switch (choice) {
case 1:
// TODO
break;
case 1: {
System.out.println("Enter username: ");
String username = scanner.next();
System.out.println("Enter password: ");
String password = scanner.next();
case 2:
// TODO
User user = authService.login(username, password);
if (user == null) {
System.err.println("Unable to login");
continue;
}
System.out.println("welcome! " + user.getUsername());
MenuService menuService = new MenuService();
menuService.showMenu();
break;
}
case 2: {
System.out.println("Enter username: ");
String username = scanner.nextLine();
System.out.println("Enter password: ");
String password = scanner.nextLine();
System.out.println("Enter email: ");
String email = scanner.nextLine();
if (!authService.register(username, password, email)) {
System.err.println("Registration failed.");
continue;
}
System.out.println("Registered successfully.");
break;
}
case 3:
return;