From c4b31bc54892239fee9141d9a1dad2b2040be952 Mon Sep 17 00:00:00 2001 From: Malte Schulze Hobeling Date: Thu, 5 Jan 2023 05:06:19 +0100 Subject: [PATCH 1/4] did some stuff --- .../AccountMgr.java | 93 +++++++ .../ConsoleLib.java | 221 +++++++++++++++ .../ConsoleMain.java | 137 ++++++++++ .../essensbestellungsverwaltung/Database.java | 252 +++++++++++++++--- .../essensbestellungsverwaltung/FoodMgr.java | 46 ++++ .../HelloApplication.java | 2 +- .../SuperMain.java | 2 +- 7 files changed, 711 insertions(+), 42 deletions(-) create mode 100644 src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java create mode 100644 src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java create mode 100644 src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java create mode 100644 src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java b/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java new file mode 100644 index 0000000..16df9d5 --- /dev/null +++ b/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java @@ -0,0 +1,93 @@ +package com.bib.essensbestellungsverwaltung; +/* + @author Malte Schulze Hobeling + */ +public class AccountMgr { + /** + * creates a user with createUser(...) and adds its id to the 'worker' table + * @param userData String[] name, firstname, password, email + * @param addressData String[] street, number, plz, city + * @return userid or -1 + */ + public static long createWorker(String[] userData, String[] addressData){ + long id = createUser(userData, addressData); + String sId = String.valueOf(id); + Database.insert("worker", new String[]{"userid"}, new String[]{sId}); + return id; + } + + /** + * creates a user with createUser(...) and adds its id to the 'parent' table + * @param userData String[] name, firstname, password, email + * @param addressData String[] street, number, plz, city + * @return userid or -1 + */ + public static long createParent(String[] userData, String[] addressData){ + long id = createUser(userData, addressData); + String sId = String.valueOf(id); + Database.insert("parent", new String[]{"userid"}, new String[]{sId}); + return id; + } + + /** + * adds a user to the database + * @param userData String[] name, firstname, password, email + * @param addressData String[] street, number, plz, city + * @return userid or -1 + */ + private static long createUser(String[] userData, String[] addressData) { + String[] addressH = {"street", "number", "plz", "city"}; + String[] userH = {"name", "firstname", "addressid", "password", "email"}; + String name = userData[0]; + String firstname = userData[1]; + String pw = userData[2]; + String email = userData[3]; + + long id = Database.insert("address", addressH, addressData); + String sId = String.valueOf(id); + String[] userD = {name, firstname, sId, pw, email}; + id = Database.insert("user", userH, userD); + return id; + } + + public static long createChild(String[] childData,String[] allergyData, String[] severityData){ + String[] childH = {"name","firstname","addressid"}; + String[] child_allergyH = {"childid","allergyid","severityid"}; + long id = Database.insert("child", childH, childData); + if(allergyData.length > 0){ + for(int i = 0; i < allergyData.length; i++){ + String sId = String.valueOf(id); + String[] child_allergyD = {sId,allergyData[i],severityData[i]}; + Database.insert("child_allergy",child_allergyH,child_allergyD); + } + } + return id; + } + + public static long matchParentChild(String parentId, String childId){ + String[] parent_childH = {"parentuserid","childid"}; + String[] parent_childD = {parentId,childId}; + return Database.insert("parent_child", parent_childH,parent_childD); + } + + public static long login(String email, String pw){ + String[] userH = {"email","password"}; + String[] userD = {email,pw}; + return Database.getSingleId("user",userH,userD); + } + + public static boolean isWorker(String id){ + String[] workerH = {"userid"}; + String[] workerD = {id}; + long workerId = Database.getSingleId("worker",workerH,workerD); + return workerId > 0; + } + + + public static boolean isParent(String id){ + String[] parentH = {"userid"}; + String[] parentD = {id}; + long parentId = Database.getSingleId("parent",parentH,parentD); + return parentId > 0; + } +} diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java new file mode 100644 index 0000000..bf70d00 --- /dev/null +++ b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java @@ -0,0 +1,221 @@ +package com.bib.essensbestellungsverwaltung; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class ConsoleLib { + public static void createWorkerPrompt(){ + Scanner sc = new Scanner(System.in); + System.out.println("Registrierung eines neuen Mitarbeiters"); + String[] userData = new String[4]; + String[] addressData = new String[4]; + System.out.print("Nachname: "); + userData[0] = sc.nextLine(); + System.out.print("Vorname: "); + userData[1] = sc.nextLine(); + System.out.print("Straße: "); + addressData[0] = sc.nextLine(); + System.out.print("Hausnummer: "); + addressData[1] = sc.nextLine(); + System.out.print("Postleitzahl: "); + addressData[2] = sc.nextLine(); + System.out.print("Stadt: "); + addressData[3] = sc.nextLine(); + System.out.print("Email: "); + userData[3] = sc.nextLine(); + System.out.print("Passwort: "); + userData[2] = sc.nextLine(); + long id = AccountMgr.createWorker(userData,addressData); + if(id < 1){ + System.out.println("Fehler beim erstellen"); + } + } + + public static void createParentPrompt(){ + Scanner sc = new Scanner(System.in); + System.out.println("Registrierung eines neuen Elternteils"); + String[] userData = new String[4]; + String[] addressData = new String[4]; + System.out.print("Nachname: "); + userData[0] = sc.nextLine(); + System.out.print("Vorname: "); + userData[1] = sc.nextLine(); + System.out.print("Straße: "); + addressData[0] = sc.nextLine(); + System.out.print("Hausnummer: "); + addressData[1] = sc.nextLine(); + System.out.print("Postleitzahl: "); + addressData[2] = sc.nextLine(); + System.out.print("Stadt: "); + addressData[3] = sc.nextLine(); + System.out.print("Email: "); + userData[3] = sc.nextLine(); + System.out.print("Passwort: "); + userData[2] = sc.nextLine(); + long id = AccountMgr.createParent(userData,addressData); + if(id < 1){ + System.out.println("Fehler beim erstellen"); + } + } + + public static void createChildPrompt(String parentId){ + Scanner sc = new Scanner(System.in); + String[] childData = new String[3]; + System.out.println("Registrierung eines neuen Kindes"); + System.out.print("Nachname: "); + childData[0] = sc.nextLine(); + System.out.print("Vorname: "); + childData[1] = sc.nextLine(); + System.out.println("Bitte geben Sie die Nummer der passenden Adresse an: "); + for (String s : Database.getTable("address")) { + String[] parts = s.split(":"); + System.out.printf("Nr.: %s Straße: %s Hausnr.: %s PLZ: %s Stadt: %s%n",parts[0],parts[1],parts[2],parts[3],parts[4]); + } + System.out.print("Adressnummer: "); + childData[2] = sc.nextLine(); + for (String s : Database.getTable("allergy")) { + String[] parts = s.split(":"); + System.out.printf("Nr. %s %s%n",parts[0],parts[1]); + } + System.out.println("Bitte Geben Sie die Nr der Allergien und Ihre Schwere an: "); + System.out.print("Allergien (Nr mit , getrennt[1,4,5,16]): "); + String allergies = sc.nextLine(); + String[] allergyData = allergies.split(","); + System.out.print("Schweren (1 Harmlos - 3 Kritisch[2,3,1,3]): "); + String severities = sc.nextLine(); + String[] severityData = severities.split(","); + long id = AccountMgr.createChild(childData,allergyData,severityData); + if(id < 1){ + System.out.println("Fehler beim erstellen"); + return; + } + String sId = String.valueOf(id); + if(AccountMgr.matchParentChild(parentId,sId) == -1){ + System.out.println("Fehler beim verknüpfen"); + } + } + + public static void createFoodPrompt(){ + Scanner sc = new Scanner(System.in); + String[] foodData = new String[4]; + System.out.println("Registrierung eines neuen Essens"); + System.out.print("Name: "); + foodData[0] = sc.nextLine(); + System.out.print("Beschreibung: "); + foodData[1] = sc.nextLine(); + System.out.print("Ist es ein Dessert?[0/1]: "); + foodData[2] = sc.nextLine(); + System.out.print("Ist es vegan[1], vegetarisch[2] oder fleischhaltig[3]: "); + foodData[3] = sc.nextLine(); + for (String s : Database.getTable("allergy")) { + String[] parts = s.split(":"); + System.out.printf("Nr. %s %s%n",parts[0],parts[1]); + } + System.out.println("Bitte geben Sie die Nr. aller zutreffenden Allergien mit Komma getrennt an [1,3,6]"); + System.out.print("Allergienummer: "); + String allergies = sc.nextLine(); + String[] allergyData = allergies.split(","); + FoodMgr.createFood(foodData,allergyData); + } + + public static long loginPrompt(){ + System.out.println("Login"); + Scanner sc = new Scanner(System.in); + long id = -1; + while (id == -1){ + System.out.print("Email: "); + String email = sc.nextLine(); + System.out.print("Passwort: "); + String pw = sc.nextLine(); + id = AccountMgr.login(email,pw); + if(id == -1){ + System.out.println("Login fehlgeschlagen"); + } + } + System.out.println("Login erfolgreich"); + return id; + } + + public static void matchParentChildPrompt(String parentId){ + System.out.println("Wählen Sie ihr Kind aus: "); + Database.getTable("child"); + Scanner sc = new Scanner(System.in); + System.out.print("Nr: "); + String childId = sc.nextLine(); + if(AccountMgr.matchParentChild(parentId,childId) == -1){ + System.out.println("Fehler"); + } + } + + public static void tablePrompt(){ + Scanner sc = new Scanner(System.in); + System.out.print("Table: "); + String table = sc.nextLine(); + printConsole(Database.getTable(table)); + } + + public static void printConsole(List list){ + for (String entry : list) { + System.out.println(entry); + } + } + + public static void createFood_planPrompt(){ + System.out.println("Erstellen eines Essensplans"); + String[] food_planData = new String[5]; + Scanner sc = new Scanner(System.in); + System.out.print("Bitte geben Sie das Datum im Format YYYY-MM-DD an: "); + food_planData[0] = sc.nextLine(); + printConsole(FoodMgr.getVeganFood(false)); + System.out.print("Veganes Hauptgericht Nr: "); + food_planData[1] = sc.nextLine(); + printConsole(FoodMgr.getFood(false)); + System.out.print("Zweites Hauptgericht Nr: "); + food_planData[2] = sc.nextLine(); + printConsole(FoodMgr.getVeganFood(true)); + System.out.print("Veganes Dessert Nr: "); + food_planData[3] = sc.nextLine(); + printConsole(FoodMgr.getFood(true)); + System.out.print("Zweites Dessert Nr: "); + food_planData[4] = sc.nextLine(); + long id = FoodMgr.createFood_plan(food_planData); + if(id < 0){ + System.out.println("Fehler"); + } + } + + public static void showFood_planPrompt(){ + System.out.println("Essensplan zum Anzeigen auswählen"); + Scanner sc = new Scanner(System.in); + System.out.print("Bitte geben Sie das Datum im Format YYYY-MM-DD an: "); + String date = sc.nextLine(); + List plan = FoodMgr.getFood_plan(date); + List food = new ArrayList<>(); + StringBuilder sb; + for (String day : plan) { + sb = new StringBuilder(); + String[] parts = day.split(":"); + sb.append("Tag: "); + sb.append(parts[1]); + sb.append(" Veganesgericht: "); + food = FoodMgr.getFoodById(Long.parseLong(parts[2])); + String[] foodParts = food.get(0).split(":"); + sb.append(foodParts[1]); + sb.append(" Zweites Hauptgericht: "); + food = FoodMgr.getFoodById(Long.parseLong(parts[3])); + foodParts = food.get(0).split(":"); + sb.append(foodParts[1]); + sb.append(" Veganesdessert: "); + food = FoodMgr.getFoodById(Long.parseLong(parts[4])); + foodParts = food.get(0).split(":"); + sb.append(foodParts[1]); + sb.append(" Zweites Dessert: "); + food = FoodMgr.getFoodById(Long.parseLong(parts[5])); + foodParts = food.get(0).split(":"); + sb.append(foodParts[1]); + food.add(sb.toString()); + } + printConsole(food); + } +} diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java new file mode 100644 index 0000000..df06c97 --- /dev/null +++ b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java @@ -0,0 +1,137 @@ +package com.bib.essensbestellungsverwaltung; + +import java.util.List; +import java.util.Scanner; + +public class ConsoleMain { + static long currentUserId = -1; + static boolean isWorker = false; + static boolean isParent = false; + public static void main(String[] args) { + boolean firstRun = Database.init(); + Database.createDb(); + Database.fillDb(); + //Database.printSampleQuery(); + if(firstRun){ + ConsoleLib.createWorkerPrompt(); + } + while (true){ + if(currentUserId == -2){ + break; + }else if(currentUserId < 0){ + defaultMenu(); + }else{ + if(isWorker){ + adminMenu(); + }else if(isParent){ + parentMenu(); + } + } + } + } + + public static void defaultMenu(){ + System.out.println("1: Login"); + System.out.println("2: Essensplan anzeigen"); + System.out.println("3: Programm beenden"); + + System.out.print("Auswahl: "); + Scanner sc = new Scanner(System.in); + String selection = sc.nextLine(); + switch (selection){ + case "1": + currentUserId = ConsoleLib.loginPrompt(); + isWorker = AccountMgr.isWorker(String.valueOf(currentUserId)); + isParent = AccountMgr.isParent(String.valueOf(currentUserId)); + break; + case "2": + ConsoleLib.showFood_planPrompt(); + break; + case "3": + currentUserId = -2; + break; + } + } + + public static void adminMenu(){ + System.out.println("0: Ausloggen"); + System.out.println("1: Einen neuen Mitarbeiter anlegen"); + System.out.println("2: Ein neues Elternteil anlegen"); + System.out.println("3: Ein neues Kind anlegen"); + System.out.println("4: Kind einem Elternteil zuordnen"); + System.out.println("5: Ein neues Essen anlegen"); + System.out.println("6: Table"); + System.out.println("7: Einen Essensplan erstellen"); + System.out.println("8: Essensplan anzeigen"); + + + System.out.print("Auswahl: "); + Scanner sc = new Scanner(System.in); + String selection = sc.nextLine(); + switch (selection){ + case "0": + currentUserId = -1; + isWorker = false; + isParent = false; + break; + case "1": + ConsoleLib.createWorkerPrompt(); + break; + case "2": + ConsoleLib.createParentPrompt(); + break; + case "3": + ConsoleLib.createChildPrompt(String.valueOf(currentUserId)); + break; + case "4": + ConsoleLib.matchParentChildPrompt(String.valueOf(currentUserId)); + break; + case "5": + ConsoleLib.createFoodPrompt(); + break; + case "6": + ConsoleLib.tablePrompt(); + break; + case "7": + ConsoleLib.createFood_planPrompt(); + break; + case "8": + ConsoleLib.showFood_planPrompt(); + break; + default: + break; + } + + } + + public static void parentMenu(){ + System.out.println("0: Ausloggen"); + System.out.println("3: Ein neues Kind anlegen"); + System.out.println("4: Kind einem Elternteil zuordnen"); + + + System.out.print("Auswahl: "); + Scanner sc = new Scanner(System.in); + String selection = sc.nextLine(); + switch (selection){ + case "0": + currentUserId = -1; + isWorker = false; + isParent = false; + break; + case "3": + ConsoleLib.createChildPrompt(String.valueOf(currentUserId)); + break; + case "4": + ConsoleLib.matchParentChildPrompt(String.valueOf(currentUserId)); + break; + case "6": + ConsoleLib.tablePrompt(); + break; + default: + break; + } + + } + +} diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/Database.java b/src/main/java/com/bib/essensbestellungsverwaltung/Database.java index 5fd7fce..cb55dcb 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/Database.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/Database.java @@ -1,6 +1,6 @@ package com.bib.essensbestellungsverwaltung; /* - @author Malte Schulze Hobeling + @author Malte Schulze Hobeling */ import java.io.File; @@ -13,10 +13,10 @@ import java.util.List; public class Database { private static final String dbLocation = "jdbc:sqlite:"+Path.of("").toAbsolutePath()+"/database.db"; - protected static void init(){ + protected static boolean init(){ File db = new File(Path.of("").toAbsolutePath()+"/database.db"); try { - db.createNewFile(); + return db.createNewFile(); } catch (IOException e) { throw new RuntimeException(e); } @@ -44,17 +44,17 @@ public class Database { sql[1] = """ CREATE TABLE IF NOT EXISTS food_type ( id integer PRIMARY KEY, - name text + name text UNIQUE );"""; sql[2] = """ CREATE TABLE IF NOT EXISTS allergy ( id integer PRIMARY KEY, - name text + name text UNIQUE );"""; sql[3] = """ CREATE TABLE IF NOT EXISTS severity ( id integer PRIMARY KEY, - severity integer + name text UNIQUE );"""; sql[4] = """ CREATE TABLE IF NOT EXISTS user ( @@ -105,7 +105,7 @@ public class Database { sql[10] = """ CREATE TABLE IF NOT EXISTS food ( id integer PRIMARY KEY, - name text, + name text UNIQUE, description text, isdessert integer, food_typeid integer, @@ -125,7 +125,7 @@ public class Database { FOREIGN KEY(dessert2) REFERENCES food(id) );"""; sql[12] = """ - CREATE TABLE IF NOT EXISTS food_restrictions ( + CREATE TABLE IF NOT EXISTS food_restriction ( id integer PRIMARY KEY, foodid integer, allergyid integer, @@ -150,7 +150,7 @@ public class Database { } } - protected static void fillSampleDb(){ + protected static void fillDb(){ List sqls = new ArrayList<>(); sqls.add(""" INSERT OR IGNORE INTO food_type (id,name) @@ -227,6 +227,15 @@ public class Database { sqls.add(""" INSERT OR IGNORE INTO allergy (id,name) VALUES('22','Konservierungsstoff');"""); + sqls.add(""" + INSERT OR IGNORE INTO severity (id,name) + VALUES('1','Harmlos');"""); + sqls.add(""" + INSERT OR IGNORE INTO severity (id,name) + VALUES('2','Warnung');"""); + sqls.add(""" + INSERT OR IGNORE INTO severity (id,name) + VALUES('3','Kritisch');"""); try(Connection conn = connect(); Statement stmt = conn.createStatement()){ for (String sql : sqls) { stmt.execute(sql); @@ -236,16 +245,65 @@ public class Database { } } - protected static boolean insert(String table, String header, String values){ - try (Connection conn = connect(); Statement stmt = conn.createStatement()){ - String sql = "INSERT OR IGNORE INTO " + table + " (" + header + ") VALUES(" + values + ");"; - stmt.execute(sql); + /** + * inserts data into table and returns its id + * @param table name of the database table + * @param header String[] order should match with values + * @param values String[] order should match with header + * @return id of dataset or -1 + */ + protected static long insert(String table, String[] header, String[] values){ + long id = -1; + try (Connection conn = connect()){ + String query = queryBuilder("exists",table,header,values); + PreparedStatement psQuery = conn.prepareStatement(query); + ResultSet rsQuery = psQuery.executeQuery(); + if(rsQuery.next()){ + boolean found = rsQuery.getBoolean(1); + if(!found){ + String sql = queryBuilder("insert",table,header,values); + String[] rowId = {"id"}; + PreparedStatement ps = conn.prepareStatement(sql,rowId); + ps.execute(); + ResultSet rs = ps.getGeneratedKeys(); + if(rs.next()){ + id = rs.getLong(1); + } + + }else{ + query = queryBuilder("selectMatch",table,header,values); + psQuery = conn.prepareStatement(query); + rsQuery = psQuery.executeQuery(); + if(rsQuery.next()) { + id = rsQuery.getLong(1); + } + } + } + } catch (SQLException e) { - return false; + return id; } - return true; + return id; } + protected static long getSingleId(String table, String[] header, String[] values){ + long id = -1; + try(Connection conn = connect()){ + String sql = queryBuilder("selectMatch",table,header,values); + PreparedStatement ps = conn.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + if(rs.next()){ + id = rs.getLong(1); + if(rs.next()){ + id = -1; + } + } + }catch (SQLException e){ + e.printStackTrace(); + return id; + } + return id; + } protected static void printSampleQuery(){ String sql = """ @@ -253,17 +311,17 @@ public class Database { String sql1 = """ SELECT * FROM allergy WHERE id > ?;"""; try(Connection conn = connect()){ - PreparedStatement pstmt = conn.prepareStatement(sql); - PreparedStatement pstmt1 = conn.prepareStatement(sql1); - pstmt.setInt(1,0); - ResultSet rs = pstmt.executeQuery(); + PreparedStatement ps = conn.prepareStatement(sql); + PreparedStatement ps1 = conn.prepareStatement(sql1); + ps.setInt(1,0); + ResultSet rs = ps.executeQuery(); System.out.println("food_type"); while (rs.next()){ System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); } System.out.println("allergy"); - pstmt1.setInt(1,0); - rs = pstmt1.executeQuery(); + ps1.setInt(1,0); + rs = ps1.executeQuery(); while (rs.next()){ System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); } @@ -275,32 +333,146 @@ public class Database { protected static void deleteSample(){ String sql = """ DELETE FROM user WHERE id = ?;"""; - try(Connection conn = connect();PreparedStatement pstmt = conn.prepareStatement(sql)){ - pstmt.setInt(1,1); - pstmt.executeUpdate(); + try(Connection conn = connect();PreparedStatement ps = conn.prepareStatement(sql)){ + ps.setInt(1,1); + ps.executeUpdate(); }catch (SQLException e){ e.printStackTrace(); } } - /* String sql = """ - CREATE TABLE IF NOT EXISTS user ( - id integer PRIMARY KEY, - name text);"""; - String sql2 = "SELECT * FROM user WHERE id > ?"; - String sql3 = "INSERT INTO user (id,name) VALUES (1,'test1')"; - try(Connection conn = connect(); - Statement stmt = conn.createStatement()){ - stmt.execute(sql); - stmt.execute(sql3); - PreparedStatement pstmt = conn.prepareStatement(sql2); - pstmt.setInt(1,0); - ResultSet rs = pstmt.executeQuery(); + private static String queryBuilder(String type,String table, String[] header, String[] values){ + String sql; + StringBuilder sb = new StringBuilder(); + switch (type){ + case "exists": + sb = new StringBuilder("SELECT (count(*) > 0) as found FROM "); + sb.append(table); + sb.append(" WHERE "); + sb.append(header[0]); + sb.append(" LIKE '"); + sb.append(values[0]); + sb.append("'"); + for (int i = 1; i < header.length; i++){ + sb.append(" AND "); + sb.append(header[i]); + sb.append(" LIKE '"); + sb.append(values[i]); + sb.append("'"); + } + break; + case "selectMatch": + sb = new StringBuilder("SELECT * FROM "); + sb.append(table); + sb.append(" WHERE "); + sb.append(header[0]); + sb.append(" LIKE '"); + sb.append(values[0]); + sb.append("'"); + for (int i = 1; i < header.length; i++){ + sb.append(" AND "); + sb.append(header[i]); + sb.append(" LIKE '"); + sb.append(values[i]); + sb.append("'"); + } + break; + case "insert": + sb = new StringBuilder("INSERT OR IGNORE INTO "); + sb.append(table); + sb.append(" ("); + sb.append(header[0]); + for(int i = 1; i < header.length; i++){ + sb.append(","); + sb.append(header[i]); + } + sb.append(") VALUES('"); + sb.append(values[0]); + sb.append("'"); + for (int i = 1; i < values.length; i++){ + sb.append(",'"); + sb.append(values[i]); + sb.append("'"); + } + sb.append(");"); + break; + } + sql = sb.toString(); + return sql; + } + + protected static List getTable(String table){ + List data = new ArrayList<>(); + StringBuilder sb; + try(Connection conn = connect()) { + String sql = "SELECT * FROM " + table; + PreparedStatement ps = conn.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + ResultSetMetaData rsmd = rs.getMetaData(); + int count = rsmd.getColumnCount(); while (rs.next()){ - System.out.println(rs.getInt("id")); + sb = new StringBuilder(); + sb.append(rs.getString(1)); + for(int i = 2; i <= count; i++){ + sb.append(":"); + sb.append(rs.getString(i)); + } + data.add(sb.toString()); + } + }catch (SQLException e){ + return new ArrayList<>(); + } + return data; + } + + protected static List select(String table,String[] header, String[] values){ + List data = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); + String sql = queryBuilder("selectMatch",table,header,values); + try(Connection conn = connect()) { + PreparedStatement ps = conn.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + ResultSetMetaData rsmd = rs.getMetaData(); + int count = rsmd.getColumnCount(); + while (rs.next()){ + sb = new StringBuilder(); + sb.append(rs.getString(1)); + for(int i = 2; i <= count; i++){ + sb.append(":"); + sb.append(rs.getString(i)); + } + data.add(sb.toString()); } }catch (SQLException e){ e.printStackTrace(); - return; - } */ + return data; + } + return data; + } + + protected static List getEntryById(String table, long id){ + List data = new ArrayList<>(); + StringBuilder sb; + String sql = "SELECT * FROM " + table + " WHERE id = ?;"; + try (Connection conn = connect()) { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setLong(1,id); + ResultSet rs = ps.executeQuery(); + ResultSetMetaData rsmd = rs.getMetaData(); + int count = rsmd.getColumnCount(); + while (rs.next()){ + sb = new StringBuilder(); + sb.append(rs.getString(1)); + for(int i = 2; i <= count; i++){ + sb.append(":"); + sb.append(rs.getString(i)); + } + data.add(sb.toString()); + } + } catch (SQLException e) { + e.printStackTrace(); + return data; + } + return data; + } } diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java b/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java new file mode 100644 index 0000000..6d9b065 --- /dev/null +++ b/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java @@ -0,0 +1,46 @@ +package com.bib.essensbestellungsverwaltung; + +import java.util.List; + +public class FoodMgr { + public static long createFood(String[] foodData, String[] allergyData){ + String[] foodH = {"name","description","isDessert","food_typeid"}; + String[] food_restrictionH = {"foodid","allergyid"}; + long id = Database.insert("food",foodH,foodData); + if(allergyData.length > 0){ + String sId = String.valueOf(id); + for (String allergyId : allergyData) { + String[] food_restrictionD = {sId,allergyId}; + Database.insert("food_restriction",food_restrictionH, food_restrictionD); + } + } + return id; + } + + public static long createFood_plan(String[] food_planData){ + String[] food_planH = {"date","food1","food2","dessert1","dessert2"}; + return Database.insert("food_plan",food_planH,food_planData); + } + + public static List getFood(boolean isDessert){ + String[] foodH = {"isDessert"}; + String[] foodD = {(isDessert ? "1" : "0")}; + return Database.select("food",foodH,foodD); + } + + public static List getVeganFood(boolean isDessert){ + String[] foodH = {"isDessert","food_typeid"}; + String[] foodD = {(isDessert ? "1" : "0"),"1"}; + return Database.select("food",foodH,foodD); + } + + public static List getFood_plan(String date){ + String[] food_planH = {"date"}; + String[] food_planD = {date}; + return Database.select("food_plan",food_planH,food_planD); + } + + public static List getFoodById(long id){ + return Database.getEntryById("food",id); + } +} diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/HelloApplication.java b/src/main/java/com/bib/essensbestellungsverwaltung/HelloApplication.java index 03e23c7..f92150c 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/HelloApplication.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/HelloApplication.java @@ -25,7 +25,7 @@ public class HelloApplication extends Application { public static void main(String[] args) { Database.init(); Database.createDb(); - Database.fillSampleDb(); + Database.fillDb(); Database.printSampleQuery(); //Database.deleteSample(); launch(); diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/SuperMain.java b/src/main/java/com/bib/essensbestellungsverwaltung/SuperMain.java index 95d759f..e45c8f0 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/SuperMain.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/SuperMain.java @@ -2,6 +2,6 @@ package com.bib.essensbestellungsverwaltung; public class SuperMain { public static void main(String[] args) { - HelloApplication.main(args); + ConsoleMain.main(args); } } From 89ea9ca70e05a13c79d58e587801112c88996e65 Mon Sep 17 00:00:00 2001 From: Malte Schulze Hobeling Date: Fri, 6 Jan 2023 00:02:06 +0100 Subject: [PATCH 2/4] basic encryption --- .../AccountMgr.java | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java b/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java index 16df9d5..071adc8 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java @@ -1,4 +1,15 @@ package com.bib.essensbestellungsverwaltung; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.util.Arrays; +import java.util.Base64; + /* @author Malte Schulze Hobeling */ @@ -40,7 +51,7 @@ public class AccountMgr { String[] userH = {"name", "firstname", "addressid", "password", "email"}; String name = userData[0]; String firstname = userData[1]; - String pw = userData[2]; + String pw = hashAndSalt(userData[2]); String email = userData[3]; long id = Database.insert("address", addressH, addressData); @@ -72,7 +83,7 @@ public class AccountMgr { public static long login(String email, String pw){ String[] userH = {"email","password"}; - String[] userD = {email,pw}; + String[] userD = {email,hashAndSalt(pw)}; return Database.getSingleId("user",userH,userD); } @@ -90,4 +101,20 @@ public class AccountMgr { long parentId = Database.getSingleId("parent",parentH,parentD); return parentId > 0; } + + public static String hashAndSalt(String pw){ + //todo: find a better way to salt + byte[] magicSalt = new byte[]{96, 13, 100, 85, -37, 52, -123, 86, -123, -92, 16, 15, -110, -42, -49, 0}; + KeySpec spec = new PBEKeySpec(pw.toCharArray(), magicSalt,310001,256); + String hashedPw = null; + try { + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + byte[] hash = factory.generateSecret(spec).getEncoded(); + Base64.Encoder enc = Base64.getEncoder(); + hashedPw = enc.encodeToString(hash); + } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return hashedPw; + } } From 58fb02875ad6b545f7673b18265be9ad560bdf7f Mon Sep 17 00:00:00 2001 From: Malte Schulze Hobeling Date: Fri, 6 Jan 2023 01:51:42 +0100 Subject: [PATCH 3/4] added missing functionality --- .../AccountMgr.java | 21 ++--- .../ConsoleLib.java | 46 +++++++++- .../ConsoleMain.java | 86 +++++++------------ .../essensbestellungsverwaltung/Database.java | 38 ++++---- .../essensbestellungsverwaltung/FoodMgr.java | 8 ++ 5 files changed, 114 insertions(+), 85 deletions(-) diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java b/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java index 071adc8..bc85970 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java @@ -1,18 +1,15 @@ package com.bib.essensbestellungsverwaltung; - -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -import java.util.Arrays; -import java.util.Base64; - /* @author Malte Schulze Hobeling */ + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.util.Base64; + public class AccountMgr { /** * creates a user with createUser(...) and adds its id to the 'worker' table @@ -106,7 +103,7 @@ public class AccountMgr { //todo: find a better way to salt byte[] magicSalt = new byte[]{96, 13, 100, 85, -37, 52, -123, 86, -123, -92, 16, 15, -110, -42, -49, 0}; KeySpec spec = new PBEKeySpec(pw.toCharArray(), magicSalt,310001,256); - String hashedPw = null; + String hashedPw; try { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] hash = factory.generateSecret(spec).getEncoded(); diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java index bf70d00..a63fe50 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java @@ -1,4 +1,7 @@ package com.bib.essensbestellungsverwaltung; +/* + @author Malte Schulze Hobeling + */ import java.util.ArrayList; import java.util.List; @@ -116,7 +119,9 @@ public class ConsoleLib { System.out.print("Allergienummer: "); String allergies = sc.nextLine(); String[] allergyData = allergies.split(","); - FoodMgr.createFood(foodData,allergyData); + if(FoodMgr.createFood(foodData,allergyData) < 1){ + System.out.println("Fehler"); + } } public static long loginPrompt(){ @@ -155,6 +160,17 @@ public class ConsoleLib { printConsole(Database.getTable(table)); } + public static void deletePrompt(){ + Scanner sc = new Scanner(System.in); + System.out.println("Löschen"); + System.out.print("Tabelle: "); + String table = sc.nextLine(); + System.out.print("Id: "); + long id = sc.nextLong(); + sc.nextLine(); + Database.delete(table,id); + } + public static void printConsole(List list){ for (String entry : list) { System.out.println(entry); @@ -218,4 +234,32 @@ public class ConsoleLib { } printConsole(food); } + + public static void createFood_selectionPrompt(){ + System.out.println("Essensauswahl"); + Scanner sc = new Scanner(System.in); + String[] food_selectionData = new String[3]; + System.out.print("Kind ID: "); + food_selectionData[0] = sc.nextLine(); + System.out.print("Datum: "); + String date = sc.nextLine(); + String[] foodPlanParts = Database.select("food_plan", new String[]{"date"}, new String[]{date}).get(0).split(":"); + food_selectionData[1] = foodPlanParts[0]; + System.out.println("Hauptspeisen: "); + System.out.println(Database.select("food",new String[]{"food"},new String[]{foodPlanParts[2]}).get(0)); + System.out.println(Database.select("food",new String[]{"food"},new String[]{foodPlanParts[3]}).get(0)); + System.out.print("Id: "); + food_selectionData[2] = sc.nextLine(); + if(FoodMgr.createFood_selection(food_selectionData) < 1){ + System.out.println("Fehler"); + } + System.out.println("Nachspeisen: "); + System.out.println(Database.select("food",new String[]{"food"},new String[]{foodPlanParts[4]}).get(0)); + System.out.println(Database.select("food",new String[]{"food"},new String[]{foodPlanParts[5]}).get(0)); + System.out.print("Id: "); + food_selectionData[2] = sc.nextLine(); + if(FoodMgr.createFood_selection(food_selectionData) < 1){ + System.out.println("Fehler"); + } + } } diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java index df06c97..c280e99 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java @@ -1,6 +1,8 @@ package com.bib.essensbestellungsverwaltung; +/* + @author Malte Schulze Hobeling + */ -import java.util.List; import java.util.Scanner; public class ConsoleMain { @@ -38,18 +40,14 @@ public class ConsoleMain { System.out.print("Auswahl: "); Scanner sc = new Scanner(System.in); String selection = sc.nextLine(); - switch (selection){ - case "1": + switch (selection) { + case "1" -> { currentUserId = ConsoleLib.loginPrompt(); isWorker = AccountMgr.isWorker(String.valueOf(currentUserId)); isParent = AccountMgr.isParent(String.valueOf(currentUserId)); - break; - case "2": - ConsoleLib.showFood_planPrompt(); - break; - case "3": - currentUserId = -2; - break; + } + case "2" -> ConsoleLib.showFood_planPrompt(); + case "3" -> currentUserId = -2; } } @@ -63,43 +61,31 @@ public class ConsoleMain { System.out.println("6: Table"); System.out.println("7: Einen Essensplan erstellen"); System.out.println("8: Essensplan anzeigen"); + System.out.println("9: Löschen"); + System.out.println("10: Essen auswählen"); System.out.print("Auswahl: "); Scanner sc = new Scanner(System.in); String selection = sc.nextLine(); - switch (selection){ - case "0": + switch (selection) { + case "0" -> { currentUserId = -1; isWorker = false; isParent = false; - break; - case "1": - ConsoleLib.createWorkerPrompt(); - break; - case "2": - ConsoleLib.createParentPrompt(); - break; - case "3": - ConsoleLib.createChildPrompt(String.valueOf(currentUserId)); - break; - case "4": - ConsoleLib.matchParentChildPrompt(String.valueOf(currentUserId)); - break; - case "5": - ConsoleLib.createFoodPrompt(); - break; - case "6": - ConsoleLib.tablePrompt(); - break; - case "7": - ConsoleLib.createFood_planPrompt(); - break; - case "8": - ConsoleLib.showFood_planPrompt(); - break; - default: - break; + } + case "1" -> ConsoleLib.createWorkerPrompt(); + case "2" -> ConsoleLib.createParentPrompt(); + case "3" -> ConsoleLib.createChildPrompt(String.valueOf(currentUserId)); + case "4" -> ConsoleLib.matchParentChildPrompt(String.valueOf(currentUserId)); + case "5" -> ConsoleLib.createFoodPrompt(); + case "6" -> ConsoleLib.tablePrompt(); + case "7" -> ConsoleLib.createFood_planPrompt(); + case "8" -> ConsoleLib.showFood_planPrompt(); + case "9" -> ConsoleLib.deletePrompt(); + case "10" -> ConsoleLib.createFood_selectionPrompt(); + default -> { + } } } @@ -113,23 +99,17 @@ public class ConsoleMain { System.out.print("Auswahl: "); Scanner sc = new Scanner(System.in); String selection = sc.nextLine(); - switch (selection){ - case "0": + switch (selection) { + case "0" -> { currentUserId = -1; isWorker = false; isParent = false; - break; - case "3": - ConsoleLib.createChildPrompt(String.valueOf(currentUserId)); - break; - case "4": - ConsoleLib.matchParentChildPrompt(String.valueOf(currentUserId)); - break; - case "6": - ConsoleLib.tablePrompt(); - break; - default: - break; + } + case "3" -> ConsoleLib.createChildPrompt(String.valueOf(currentUserId)); + case "4" -> ConsoleLib.matchParentChildPrompt(String.valueOf(currentUserId)); + case "6" -> ConsoleLib.tablePrompt(); + default -> { + } } } diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/Database.java b/src/main/java/com/bib/essensbestellungsverwaltung/Database.java index cb55dcb..8ec8b8a 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/Database.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/Database.java @@ -114,7 +114,7 @@ public class Database { sql[11] = """ CREATE TABLE IF NOT EXISTS food_plan ( id integer PRIMARY KEY, - date text, + date text UNIQUE, food1 integer, food2 integer, dessert1 integer, @@ -137,9 +137,10 @@ public class Database { id integer PRIMARY KEY, childid integer, food_planid integer, - selection integer, + foodid integer, FOREIGN KEY(childid) REFERENCES child(id), - FOREIGN KEY(food_planid) REFERENCES food_plan(id) + FOREIGN KEY(food_planid) REFERENCES food_plan(id), + FOREIGN KEY(foodid) REFERENCES food(id) );"""; try(Connection conn = connect(); Statement stmt = conn.createStatement()){ for(int i = 0; i < sql.length; i++){ @@ -330,11 +331,10 @@ public class Database { } } - protected static void deleteSample(){ - String sql = """ - DELETE FROM user WHERE id = ?;"""; + protected static void delete(String table, long id){ + String sql = "DELETE FROM " + table + " WHERE id = ?;"; try(Connection conn = connect();PreparedStatement ps = conn.prepareStatement(sql)){ - ps.setInt(1,1); + ps.setLong(1,id); ps.executeUpdate(); }catch (SQLException e){ e.printStackTrace(); @@ -344,8 +344,8 @@ public class Database { private static String queryBuilder(String type,String table, String[] header, String[] values){ String sql; StringBuilder sb = new StringBuilder(); - switch (type){ - case "exists": + switch (type) { + case "exists" -> { sb = new StringBuilder("SELECT (count(*) > 0) as found FROM "); sb.append(table); sb.append(" WHERE "); @@ -353,15 +353,15 @@ public class Database { sb.append(" LIKE '"); sb.append(values[0]); sb.append("'"); - for (int i = 1; i < header.length; i++){ + for (int i = 1; i < header.length; i++) { sb.append(" AND "); sb.append(header[i]); sb.append(" LIKE '"); sb.append(values[i]); sb.append("'"); } - break; - case "selectMatch": + } + case "selectMatch" -> { sb = new StringBuilder("SELECT * FROM "); sb.append(table); sb.append(" WHERE "); @@ -369,33 +369,33 @@ public class Database { sb.append(" LIKE '"); sb.append(values[0]); sb.append("'"); - for (int i = 1; i < header.length; i++){ + for (int i = 1; i < header.length; i++) { sb.append(" AND "); sb.append(header[i]); sb.append(" LIKE '"); sb.append(values[i]); sb.append("'"); } - break; - case "insert": + } + case "insert" -> { sb = new StringBuilder("INSERT OR IGNORE INTO "); sb.append(table); sb.append(" ("); sb.append(header[0]); - for(int i = 1; i < header.length; i++){ + for (int i = 1; i < header.length; i++) { sb.append(","); sb.append(header[i]); } sb.append(") VALUES('"); sb.append(values[0]); sb.append("'"); - for (int i = 1; i < values.length; i++){ + for (int i = 1; i < values.length; i++) { sb.append(",'"); sb.append(values[i]); sb.append("'"); } sb.append(");"); - break; + } } sql = sb.toString(); return sql; @@ -427,7 +427,7 @@ public class Database { protected static List select(String table,String[] header, String[] values){ List data = new ArrayList<>(); - StringBuilder sb = new StringBuilder(); + StringBuilder sb; String sql = queryBuilder("selectMatch",table,header,values); try(Connection conn = connect()) { PreparedStatement ps = conn.prepareStatement(sql); diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java b/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java index 6d9b065..065d0d5 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java @@ -1,4 +1,7 @@ package com.bib.essensbestellungsverwaltung; +/* + @author Malte Schulze Hobeling + */ import java.util.List; @@ -43,4 +46,9 @@ public class FoodMgr { public static List getFoodById(long id){ return Database.getEntryById("food",id); } + + public static long createFood_selection(String[] food_selectionData){ + String[] food_selectionH = {"childid","foodplanid","foodid"}; + return Database.insert("food_selection",food_selectionH,food_selectionData); + } } From 573e17161b036bba4b68a44ec0a8935a69030834 Mon Sep 17 00:00:00 2001 From: Malte Schulze Hobeling Date: Sat, 7 Jan 2023 23:14:41 +0100 Subject: [PATCH 4/4] added invoice and order collection --- .../AccountMgr.java | 30 ++++++++++- .../ConsoleLib.java | 38 +++++++++++-- .../ConsoleMain.java | 13 +++-- .../essensbestellungsverwaltung/Database.java | 54 +++++++++++++++++++ .../essensbestellungsverwaltung/FoodMgr.java | 32 ++++++++++- .../SuperMain.java | 6 ++- 6 files changed, 160 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java b/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java index bc85970..558517f 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/AccountMgr.java @@ -8,9 +8,12 @@ import javax.crypto.spec.PBEKeySpec; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; +import java.util.ArrayList; import java.util.Base64; +import java.util.List; public class AccountMgr { + protected static double price = 5.0; /** * creates a user with createUser(...) and adds its id to the 'worker' table * @param userData String[] name, firstname, password, email @@ -91,7 +94,6 @@ public class AccountMgr { return workerId > 0; } - public static boolean isParent(String id){ String[] parentH = {"userid"}; String[] parentD = {id}; @@ -114,4 +116,30 @@ public class AccountMgr { } return hashedPw; } + + public static List getInvoice(String date, String childId){ + List invoice = new ArrayList<>(); + invoice.add("Monatsabrechnung " + date); + List child = Database.getEntryById("child", Long.parseLong(childId)); + String[] childParts = child.get(0).split(":"); + invoice.add(childParts[1] + ", " + childParts[2]); + String[] food_planH = {"date"}; + String[] food_planD = {date+"%"}; + List food_plan = Database.select("food_plan",food_planH,food_planD); + for (String day : food_plan) { + String[] food_planParts = day.split(":"); + String[] food_selectionH = {"childid","food_planid"}; + String[] food_selectionD = {childId,food_planParts[0]}; + List food_selection = Database.select("food_selection",food_selectionH,food_selectionD); + for (String food_select : food_selection) { + String[] food_selectParts = food_select.split(":"); + List food = Database.getEntryById("food",Long.parseLong(food_selectParts[3])); + String[] foodParts = food.get(0).split(":"); + String line = food_planParts[1] + ": " + foodParts[1]; + invoice.add(line); + } + } + invoice.add("Total: " + (invoice.size()-2) + " X " + price + "€ = " + ((invoice.size()-2)*price) + "€"); + return invoice; + } } diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java index a63fe50..fa9775f 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleLib.java @@ -246,20 +246,50 @@ public class ConsoleLib { String[] foodPlanParts = Database.select("food_plan", new String[]{"date"}, new String[]{date}).get(0).split(":"); food_selectionData[1] = foodPlanParts[0]; System.out.println("Hauptspeisen: "); - System.out.println(Database.select("food",new String[]{"food"},new String[]{foodPlanParts[2]}).get(0)); - System.out.println(Database.select("food",new String[]{"food"},new String[]{foodPlanParts[3]}).get(0)); + System.out.println(Database.select("food",new String[]{"id"},new String[]{foodPlanParts[2]}).get(0)); + System.out.println(Database.select("food",new String[]{"id"},new String[]{foodPlanParts[3]}).get(0)); System.out.print("Id: "); food_selectionData[2] = sc.nextLine(); if(FoodMgr.createFood_selection(food_selectionData) < 1){ System.out.println("Fehler"); } System.out.println("Nachspeisen: "); - System.out.println(Database.select("food",new String[]{"food"},new String[]{foodPlanParts[4]}).get(0)); - System.out.println(Database.select("food",new String[]{"food"},new String[]{foodPlanParts[5]}).get(0)); + System.out.println(Database.select("food",new String[]{"id"},new String[]{foodPlanParts[4]}).get(0)); + System.out.println(Database.select("food",new String[]{"id"},new String[]{foodPlanParts[5]}).get(0)); System.out.print("Id: "); food_selectionData[2] = sc.nextLine(); if(FoodMgr.createFood_selection(food_selectionData) < 1){ System.out.println("Fehler"); } } + + public static void dayOrderPrompt(){ + System.out.println("Zusammenfassung des Tages"); + System.out.print("Datum eingeben: "); + Scanner sc = new Scanner(System.in); + String date = sc.nextLine(); + List dayOrder = FoodMgr.getDayOrder(date); + for (String food : dayOrder) { + System.out.println(food); + } + } + + public static void invoicePrompt(){ + System.out.println("Monatsabrechnung"); + System.out.print("Monat(YYYY-MM): "); + Scanner sc = new Scanner(System.in); + String date = sc.nextLine(); + System.out.print("ID des Kindes: "); + String id = sc.nextLine(); + List invoice = AccountMgr.getInvoice(date,id); + printConsole(invoice); + } + + public static void changePricePrompt(){ + System.out.print("Neuer Preis: "); + Scanner sc = new Scanner(System.in); + double price = sc.nextDouble(); + sc.nextLine(); + AccountMgr.price = price; + } } diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java index c280e99..6d823e5 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/ConsoleMain.java @@ -11,10 +11,9 @@ public class ConsoleMain { static boolean isParent = false; public static void main(String[] args) { boolean firstRun = Database.init(); - Database.createDb(); - Database.fillDb(); - //Database.printSampleQuery(); if(firstRun){ + Database.createDb(); + Database.fillDb(); ConsoleLib.createWorkerPrompt(); } while (true){ @@ -63,6 +62,9 @@ public class ConsoleMain { System.out.println("8: Essensplan anzeigen"); System.out.println("9: Löschen"); System.out.println("10: Essen auswählen"); + System.out.println("11: Bestellungen des Tages sammeln"); + System.out.println("12: Monatsabrechnung"); + System.out.println("13: Preis ändern"); System.out.print("Auswahl: "); @@ -84,8 +86,9 @@ public class ConsoleMain { case "8" -> ConsoleLib.showFood_planPrompt(); case "9" -> ConsoleLib.deletePrompt(); case "10" -> ConsoleLib.createFood_selectionPrompt(); - default -> { - } + case "11" -> ConsoleLib.dayOrderPrompt(); + case "12" -> ConsoleLib.invoicePrompt(); + case "13" -> ConsoleLib.changePricePrompt(); } } diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/Database.java b/src/main/java/com/bib/essensbestellungsverwaltung/Database.java index 8ec8b8a..0e5d949 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/Database.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/Database.java @@ -119,6 +119,7 @@ public class Database { food2 integer, dessert1 integer, dessert2 integer, + issent integer DEFAULT '0', FOREIGN KEY(food1) REFERENCES food(id), FOREIGN KEY(food2) REFERENCES food(id), FOREIGN KEY(dessert1) REFERENCES food(id), @@ -396,6 +397,38 @@ public class Database { } sb.append(");"); } + case "count" -> { + sb = new StringBuilder("SELECT COUNT(*) FROM "); + sb.append(table); + sb.append(" WHERE "); + sb.append(header[0]); + sb.append(" = "); + sb.append(values[0]); + for(int i = 1; i < header.length; i++){ + sb.append(" AND "); + sb.append(header[i]); + sb.append(" = "); + sb.append(values[i]); + } + } + case "update" -> { + sb = new StringBuilder("UPDATE "); + sb.append(table); + sb.append(" SET "); + sb.append(header[1]); + sb.append(" = "); + sb.append(values[1]); + for(int i = 2; i < header.length; i++){ + sb.append(", "); + sb.append(header[i]); + sb.append(" = "); + sb.append(values[i]); + } + sb.append(" WHERE "); + sb.append(header[0]); + sb.append(" = "); + sb.append(values[0]); + } } sql = sb.toString(); return sql; @@ -475,4 +508,25 @@ public class Database { } return data; } + + protected static int count(String table,String[] header,String[] values){ + String sql = queryBuilder("count",table,header,values); + try(Connection conn = connect()) { + PreparedStatement ps = conn.prepareStatement(sql); + ResultSet rs = ps.executeQuery(); + return rs.getInt(1); + }catch (SQLException e){ + return -1; + } + } + + protected static int update(String table,String[] header,String[] values){ + try(Connection conn = connect()) { + String sql = queryBuilder("update",table,header,values); + PreparedStatement ps = conn.prepareStatement(sql); + return ps.executeUpdate(); + }catch (SQLException e){ + return -1; + } + } } diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java b/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java index 065d0d5..50d791b 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/FoodMgr.java @@ -3,6 +3,7 @@ package com.bib.essensbestellungsverwaltung; @author Malte Schulze Hobeling */ +import java.util.ArrayList; import java.util.List; public class FoodMgr { @@ -48,7 +49,34 @@ public class FoodMgr { } public static long createFood_selection(String[] food_selectionData){ - String[] food_selectionH = {"childid","foodplanid","foodid"}; - return Database.insert("food_selection",food_selectionH,food_selectionData); + String[] food_selectionH = {"childid","food_planid","foodid"}; + List food_plan = Database.getEntryById("food_plan",Long.parseLong(food_selectionData[1])); + String[] food_planParts = food_plan.get(0).split(":"); + if(Long.parseLong(food_planParts[6]) == 0){ + return Database.insert("food_selection",food_selectionH,food_selectionData); + }else { + return -1; + } + } + + public static List getDayOrder(String date){ + List orders = new ArrayList<>(); + List food_plan = getFood_plan(date); + String[] food_planParts = food_plan.get(0).split(":"); + for(int i = 2; i < 2+4; i++){ + List food = getFoodById(Long.parseLong(food_planParts[i])); + String[] foodParts = food.get(0).split(":"); + String foodName = foodParts[1]; + String[] food_selectionH = {"food_planid","foodid"}; + String[] food_selectionD = {food_planParts[0],foodParts[0]}; + int count = Database.count("food_selection",food_selectionH,food_selectionD); + orders.add(foodName+":"+count); + } + String[] updateH = {"id","issent"}; + String[] updateD = {food_planParts[0],"1"}; + if(Database.update("food_plan",updateH,updateD) < 0){ + System.out.println("Fehler"); + } + return orders; } } diff --git a/src/main/java/com/bib/essensbestellungsverwaltung/SuperMain.java b/src/main/java/com/bib/essensbestellungsverwaltung/SuperMain.java index e45c8f0..9fb076c 100644 --- a/src/main/java/com/bib/essensbestellungsverwaltung/SuperMain.java +++ b/src/main/java/com/bib/essensbestellungsverwaltung/SuperMain.java @@ -2,6 +2,10 @@ package com.bib.essensbestellungsverwaltung; public class SuperMain { public static void main(String[] args) { - ConsoleMain.main(args); + if(args.length > 0){ + ConsoleMain.main(args); + }else { + HelloApplication.main(args); + } } }