diff --git a/README.md b/README.md index 8826177..8d78fec 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,7 @@ 98110349 Arman Babaei + 98101363 M.Taha Jahani-Nezhad + 98106072 Ali Mahdavifar + +[Server repo](https://github.com/Arman17Babaei/ProjectServer) diff --git a/pom.xml b/pom.xml index c1313e1..9b92048 100644 --- a/pom.xml +++ b/pom.xml @@ -76,6 +76,17 @@ jfoenix 9.0.8 + + io.jsonwebtoken + jjwt + 0.2 + + + javax + javaee-api + 6.0 + provided + 1.9 diff --git a/src/main/java/controller/CustomerController.java b/src/main/java/controller/CustomerController.java index f088c51..42970fa 100644 --- a/src/main/java/controller/CustomerController.java +++ b/src/main/java/controller/CustomerController.java @@ -1,12 +1,17 @@ package controller; +import com.google.gson.JsonObject; import model.*; import model.exception.DefaultUser; +import java.net.HttpURLConnection; +import java.net.URL; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; +import static controller.Database.getJsonObjectFromReader; + public class CustomerController extends UserController { private Customer customerLoggedOn; @@ -16,7 +21,7 @@ public Customer getCustomerLoggedOn() { public CustomerController(Customer user, ProductController productController) { super(user, productController); - this.customerLoggedOn = (Customer) user; + this.customerLoggedOn = user; } public static Customer newDefaultUser() { @@ -30,7 +35,7 @@ private String viewPersonalInfo() { "Phone number: " + customerLoggedOn.getPhoneNumber() + "\n"; } - public void changePersonalInfo(HashMap infoToSet) { + public void changePersonalInfo(HashMap infoToSet) throws Exception { super.changePersonalInfo(infoToSet); } @@ -40,7 +45,7 @@ public void addAddress(HashMap information) { public String getPaymentCheck() { try { - long totalPrice = purchase(); + long totalPrice = purchase("e-wallet"); return "Succesfully purchased\n" + "Total price: " + totalPrice + "\n" + "Your current credit: " + customerLoggedOn.getCredit(); @@ -49,7 +54,7 @@ public String getPaymentCheck() { } } - public String viewCartProducts() throws Exception { + public String viewCartProducts() { StringBuilder stringToReturn = new StringBuilder(); stringToReturn.append("Product ID\tProduct name\tUnit price\tNumber\n"); HashMap customerCart = customerLoggedOn.getCart(); @@ -101,16 +106,25 @@ public void decreaseNumberOfProduct(String productId) { removeFromCart(productId); } - public long getTotalPrice() throws Exception { + public long getTotalPrice() { long totalPrice = 0; - for (Product product : customerLoggedOn.getCart().keySet()) { - totalPrice += product.getPrice() * customerLoggedOn.getCart().get(product); + HashMap cart = customerLoggedOn.getCart(); + for (Product product : cart.keySet()) { + totalPrice += cart.get(product) * product.getPrice(); } if (customerLoggedOn.getDiscountUsed() != null) totalPrice *= (double) (100 - customerLoggedOn.getDiscountUsed().getDiscountPercent()) / 100; return totalPrice; } + public long getProductPrice (Product product, int num) { + long totalPrice = 0; + totalPrice += product.getPrice() * num; + if (customerLoggedOn.getDiscountUsed() != null) + totalPrice *= (double) (100 - customerLoggedOn.getDiscountUsed().getDiscountPercent()) / 100; + return totalPrice; + } + public boolean validateDiscountCode(String code) { Discount discount = Database.getDiscountByCode(code); if (discount != null) { @@ -131,12 +145,15 @@ public void removeDiscountCode () { customerLoggedOn.undoUseDiscount(); } - public long purchase() throws Exception { + public long purchase(String method) throws Exception { long totalPrice = getTotalPrice(); - customerLoggedOn.payCredit(totalPrice); + if (method.equalsIgnoreCase("e-wallet") && customerLoggedOn.getCredit() < totalPrice) { + throw new Exception("Not enough credit"); + } + payEachSeller(method); + //creating log PurchaseLog newLog = createPurchaseLog(); createSellLogForAllProducts(); - payEachSeller(); customerLoggedOn.deleteDiscount(); Database.add(newLog); customerLoggedOn.addToPurchaseHistory(newLog); @@ -146,15 +163,33 @@ public long purchase() throws Exception { return totalPrice; } - private void payEachSeller() { - for (Product product : customerLoggedOn.getCart().keySet()) { - Seller seller = product.getSellers().get(0); - seller.addToCredit(product.getPrice()); - Database.update(seller, seller.getId()); + private void payEachSeller(String method) throws Exception { + HashMap cart = customerLoggedOn.getCart(); + for (Product product : cart.keySet()) { + String destId = product.getSellers().get(0).getId(); + String reply; + if (method.equalsIgnoreCase("e-wallet")) + reply = sendCreditPaymentRequest(getProductPrice(product, cart.get(product)), destId); + else + reply = sendBankPaymentRequest(getProductPrice(product, cart.get(product)), destId); + System.out.println(product.getName() + ": " + reply); } } - public void createSellLogForAllProducts() { + private String sendBankPaymentRequest(long productPrice, String destId) throws Exception { + String url = Database.getServerUrl() + "paySellerByBankAccount" + "?username=" + userLoggedOn.getUsername() + + "&password=" + userLoggedOn.getPassword() + "&money=" + productPrice + "&sourceId=" + + userLoggedOn.getBankAccountId() + "&destId=" + destId; + return sendRequestToServer(url); + } + + private String sendCreditPaymentRequest(long productPrice, String destId) throws Exception { + String url = Database.getServerUrl() + "paySellerCredit" + "?sourceId=" + userLoggedOn.getId() + + "&money=" + productPrice + "&destId=" + destId; + return sendRequestToServer(url); + } + + public void createSellLogForAllProducts() throws Exception { for (Product product : customerLoggedOn.getCart().keySet()) { SellLog log = product.createSellLog(); log.setCustomer(customerLoggedOn); @@ -163,13 +198,13 @@ public void createSellLogForAllProducts() { } } - public void addCustomerToProducts() throws Exception { + public void addCustomerToProducts() { for (Product product : this.customerLoggedOn.getCart().keySet()) { product.addBuyer(this.customerLoggedOn); } } - private PurchaseLog createPurchaseLog() throws Exception { + private PurchaseLog createPurchaseLog() { PurchaseLog log = new PurchaseLog(); log.setDate(LocalDateTime.now()); log.setAmountPaid(getTotalPrice()); diff --git a/src/main/java/controller/Database.java b/src/main/java/controller/Database.java index e53539c..1d1d6d3 100644 --- a/src/main/java/controller/Database.java +++ b/src/main/java/controller/Database.java @@ -6,70 +6,82 @@ import com.google.gson.JsonObject; import model.*; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; public class Database { - private static final ArrayList allUsers = new ArrayList<>(); - private static final ArrayList allProducts = new ArrayList<>(); - private static final ArrayList allRequests = new ArrayList<>(); - private static final ArrayList allDiscountCodes = new ArrayList<>(); - private static final ArrayList allCategories = new ArrayList<>(); - private static final ArrayList allComments = new ArrayList<>(); - private static final ArrayList allProperties = new ArrayList<>(); - private static final ArrayList allScores = new ArrayList<>(); - private static final ArrayList allPurchaseLogs = new ArrayList<>(); - private static final ArrayList allSellLogs = new ArrayList<>(); - private static final ArrayList allOffs = new ArrayList<>(); - private static final ArrayList allProductAds = new ArrayList<>(); - private static final ArrayList allPossibleManagers = new ArrayList<>(); - - public static void loadAllData() { + private static final String USER_AGENT = "Mozilla/5.0"; + private static final String serverUrl = "http://localhost:8080/"; + private static final NetworkArray allUsers = new NetworkArray<>(User.class); + private static final NetworkArray allProducts = new NetworkArray<>(Product.class); + private static final NetworkArray allRequests = new NetworkArray<>(Request.class); + private static final NetworkArray allDiscountCodes = new NetworkArray<>(Discount.class); + private static final NetworkArray allCategories = new NetworkArray<>(Category.class); + private static final NetworkArray allComments = new NetworkArray<>(Comment.class); + private static final NetworkArray allChats = new NetworkArray<>(Chat.class); + private static final NetworkArray allProperties = new NetworkArray<>(Property.class); + private static final NetworkArray allScores = new NetworkArray<>(Score.class); + private static final NetworkArray allPurchaseLogs = new NetworkArray<>(PurchaseLog.class); + private static final NetworkArray allSellLogs = new NetworkArray<>(SellLog.class); + private static final NetworkArray allOffs = new NetworkArray<>(Off.class); + private static final NetworkArray allProductAds = new NetworkArray<>(Product.class); + private static final NetworkArray allPossibleManagers = new NetworkArray<>(PossibleManager.class); + private static final NetworkArray allPossibleSupporters = new NetworkArray<>(PossibleSupporter.class); + + private static String token = "random-customer"; + + public static void loadAllData() throws Exception { makeDirectories(); loadLists(); } private static void makeDirectories() { makeDirectory(Manager.class); + makeDirectory(Supporter.class); makeDirectory(Seller.class); makeDirectory(Customer.class); makeDirectory(Product.class); - makeDirectory(JsonObject.class); + makeDirectory(Request.class); makeDirectory(Discount.class); makeDirectory(Category.class); makeDirectory(Comment.class); + makeDirectory(Chat.class); makeDirectory(Property.class); makeDirectory(Score.class); makeDirectory(PurchaseLog.class); makeDirectory(SellLog.class); makeDirectory(Off.class); makeDirectory("ProductAd"); - makeDirectory(String.class); + makeDirectory(PossibleManager.class); + makeDirectory("PossibleSupporter"); } - private static void loadLists() { + private static void loadLists() throws Exception { loadList(allUsers, Manager.class); + loadList(allUsers, Supporter.class); loadList(allUsers, Seller.class); loadList(allUsers, Customer.class); loadList(allProducts, Product.class); - loadList(allRequests, JsonObject.class); + loadList(allRequests, Request.class); loadList(allDiscountCodes, Discount.class); loadList(allCategories, Category.class); loadList(allComments, Comment.class); + loadList(allChats, Chat.class); loadList(allProperties, Property.class); loadList(allScores, Score.class); loadList(allPurchaseLogs, PurchaseLog.class); loadList(allSellLogs, SellLog.class); loadList(allOffs, Off.class); loadList(allProductAds, Product.class, "ProductAd"); - loadList(allPossibleManagers, String.class); + loadList(allPossibleManagers, PossibleManager.class); + loadList(allPossibleSupporters, PossibleSupporter.class); } private static String getPath(String folderName) { - return "Database\\" + folderName + "\\"; + return "Database\\" + folderName + "\\"; } private static String getPath(Object object) { @@ -84,12 +96,13 @@ private static void makeDirectory(String folderName) { new File(getPath(folderName)).mkdirs(); } - private static void loadList(ArrayList list, Class cls) { + private static void loadList(ArrayList list, Class cls) throws Exception { loadList(list, cls, cls.getSimpleName()); } - private static void loadList(ArrayList list, Class cls, String folderName) { - for (final File fileEntry : new File(getPath(folderName)).listFiles()) { + private static void loadList(ArrayList list, Class cls, String folderName) throws Exception { + ((NetworkArray) list).load(); +/* for (final File fileEntry : new File(getPath(folderName)).listFiles()) { try { FileReader fileReader = new FileReader(fileEntry); Object object = new Gson().fromJson(fileReader, cls); @@ -98,15 +111,135 @@ private static void loadList(ArrayList list, Class cls, Stri } catch (Exception e) { e.printStackTrace(); } + }*/ + } + + public static Object getObjectFromNetwork(String objectId, Class objectClass) throws Exception { + JsonObject jsonObject = sendGET("resource", objectClass.getSimpleName(), objectId); + return new Gson().fromJson(jsonObject.get("object"), Class.forName("model." + jsonObject.get("className").getAsString())); + } + + public static JsonObject sendGET(String url, String objectClass, String objectId) throws Exception { + return sendGET(url + "?className=" + objectClass + "&objectId=" + objectId); + } + + public static JsonObject sendGET(String url) throws Exception { + url = serverUrl + url; + System.out.println(url); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("AuthToken", token); + con.setRequestProperty("User-Agent", USER_AGENT); + int responseCode = con.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = convertedObject.get("token").getAsString(); + + return convertedObject; + } + + public static JsonObject sendGETall(Class className) throws Exception { + return sendGET("allResources?className=" + className.getSimpleName()); + } + + + private static void sendPost(String url, String objectClass, String objectId, Object object) throws Exception { + url = serverUrl + url; + System.out.println(url + objectClass + objectId); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + con.setRequestMethod("POST"); + con.setRequestProperty("Content-Type", "application/json; utf-8"); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("AuthToken", token); + con.setRequestProperty("User-Agent", USER_AGENT); + con.setDoOutput(true); + try (OutputStream os = con.getOutputStream()) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("className", objectClass); + jsonObject.addProperty("objectId", objectId); + jsonObject.addProperty("token", token); + jsonObject.add("object", new Gson().toJsonTree(object).getAsJsonObject()); + String jsonInputString = new Gson().toJson(jsonObject); + byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8); + os.write(input, 0, input.length); } + int responseCode = con.getResponseCode(); + System.out.println("POST Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = convertedObject.get("token").getAsString(); + } + + public static void sendPOSTsellerPort(int port) throws Exception { + String url = serverUrl + "p2p"; + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + con.setRequestMethod("POST"); + con.setRequestProperty("Content-Type", "application/json; utf-8"); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("AuthToken", token); + con.setRequestProperty("User-Agent", USER_AGENT); + con.setDoOutput(true); + try (OutputStream os = con.getOutputStream()) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("token", token); + jsonObject.addProperty("port", Integer.toString(port)); + String jsonInputString = new Gson().toJson(jsonObject); + byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8); + os.write(input, 0, input.length); + } + int responseCode = con.getResponseCode(); + System.out.println("POST Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = convertedObject.get("token").getAsString(); + } + + public static JsonObject getJsonObjectFromReader(HttpURLConnection con, int responseCode) throws Exception { + BufferedReader in; + if (responseCode >= 200 && responseCode < 300) { + in = new BufferedReader(new InputStreamReader(con.getInputStream())); + } else { + in = new BufferedReader(new InputStreamReader(con.getErrorStream())); + String json = getStringFromReader(in); + JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); + con.disconnect(); + throw new Exception("Network Error: " + convertedObject.get("error").getAsString()); + } + String json = getStringFromReader(in); + con.disconnect(); + return new Gson().fromJson(json, JsonObject.class); + } + + + private static String getStringFromReader(BufferedReader in) throws IOException { + String inputLine; + StringBuilder response = new StringBuilder(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + return response.toString(); } - static void writeObject(Object object, String id) { + + static void writeObject(Object object, String id) throws Exception { writeObject(object, id, object.getClass().getSimpleName()); } - static void writeObject(Object object, String id, String folderName) { - String fileName = getPath(folderName) + id + ".json"; + static void writeObject(Object object, String id, String folderName) throws Exception { + sendPost("resource", folderName, id, object); + +/* String fileName = getPath(folderName) + id + ".json"; FileWriter writer; try { writer = new FileWriter(fileName); @@ -114,7 +247,7 @@ static void writeObject(Object object, String id, String folderName) { writer.close(); } catch (IOException e) { e.printStackTrace(); - } + }*/ } private static void deleteObject(Object object, String id) { @@ -123,6 +256,23 @@ private static void deleteObject(Object object, String id) { private static void deleteObject(String id, String folderName) { try { + String url = serverUrl + "resource?" + "id=" + id + "&folderName=" + folderName; + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setDoOutput(true); + con.setInstanceFollowRedirects(false); + con.setRequestMethod("DELETE"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + con.setRequestProperty("charset", "utf-8"); + con.setRequestProperty("AuthToken", token); + con.setUseCaches(false); + + int responseCode = con.getResponseCode(); + System.out.println("DELETE Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = convertedObject.get("token").getAsString(); File file = new File(getPath(folderName) + id + ".json"); file.delete(); } catch (Exception e) { @@ -130,64 +280,87 @@ private static void deleteObject(String id, String folderName) { } } - public static void addPossibleManager(String username) { - if (!allPossibleManagers.contains(username)) { - allPossibleManagers.add(username); + public static void addPossibleManager(String username) throws Exception { + PossibleManager possibleManager = new PossibleManager(username); + if (!allPossibleManagers.contains(possibleManager)) { + allPossibleManagers.add(new PossibleManager(username)); } - writeObject(username, username); + writeObject(possibleManager, possibleManager.getId()); } - public static void add(User user) { + public static void addPossibleSupporter(String username) throws Exception { + PossibleSupporter possibleSupporter = new PossibleSupporter(username); + if (!allPossibleSupporters.contains(possibleSupporter)) { + allPossibleSupporters.add(possibleSupporter); + } + writeObject(possibleSupporter, possibleSupporter.getId()); + } + + public static ArrayList getOnlineUsers() { + try { + JsonObject jsonObject = sendGET("onlineUsers"); + System.out.println(new Gson().fromJson(jsonObject.get("list"), ArrayList.class).toString()); + return new Gson().fromJson(jsonObject.get("list"), ArrayList.class); + } catch (Exception e) { + e.printStackTrace(); + return new ArrayList<>(); + } + } + + + public static void add(User user) throws Exception { allUsers.add(user); writeObject(user, user.getId()); } - public static void add(Product product) { - for (Product productIn : allProducts) { - if (productIn.equals(product.getId())) { - allProducts.remove(productIn); - } - } + public static void add(Product product) throws Exception { + allProducts.removeIf(productIn -> productIn.getId().equals(product.getId())); allProducts.add(product); writeObject(product, product.getId()); } - public static void add(JsonObject request) { - allRequests.add(request); - writeObject(request, request.getAsJsonObject().get("id").getAsString()); + public static void add(JsonObject request) throws Exception { + Request req = new Request(request); + allRequests.add(req); + writeObject(req, req.getId()); } - public static void add(Discount discount) { + public static void add(Discount discount) throws Exception { allDiscountCodes.add(discount); writeObject(discount, discount.getId()); } - public static void add(Category category) { + public static void add(Category category) throws Exception { allCategories.add(category); writeObject(category, category.getId()); } - public static void add(Comment comment) { + public static void add(Comment comment) throws Exception { allComments.add(comment); writeObject(comment, comment.getId()); } - public static void add(Property property) { + public static void add(Chat chat) throws Exception { + allChats.add(chat); + writeObject(chat, chat.getId()); + } + + public static void add(Property property) throws Exception { allProperties.add(property); writeObject(property, property.getId()); } - public static void add(Score score) { + public static void add(Score score) throws Exception { allScores.add(score); writeObject(score, score.getId()); } - public static void add(PurchaseLog log) { + public static void add(PurchaseLog log) throws Exception { allPurchaseLogs.add(log); writeObject(log, log.getId()); } - public static void add (SellLog log) { + public static void add(SellLog log) throws Exception { allSellLogs.add(log); writeObject(log, log.getId()); } @@ -198,7 +371,7 @@ public static void add(Off off) throws Exception { writeObject(off, off.getId()); } - public static void addProductToAds(Product product) { + public static void addProductToAds(Product product) throws Exception { allProductAds.add(product); writeObject(product, product.getId(), "ProductAd"); } @@ -219,6 +392,11 @@ public static void remove(JsonElement jsonElement) { deleteObject(jsonElement, jsonElement.getAsJsonObject().get("id").getAsString()); } + public static void remove(Request request) { + allRequests.remove(request); + deleteObject(request, request.getId()); + } + public static void removePossibleManager(String username) { allPossibleManagers.remove(username); deleteObject(username, username); @@ -235,6 +413,18 @@ public static Product getProductById(String id) throws Exception { return product; } throw new Exception("product id not found"); +// try { +// System.out.println("get product by id"); +// JsonObject jsonObject = sendGET("resource", "Product", id); +// return new Gson().fromJson(jsonObject.get("object"), Product.class); +// } catch (Exception e) { +// e.printStackTrace(); +// for (Product product : allProducts) { +// if (product.getId().equals(id)) +// return product; +// } +// throw new Exception("product id not found"); +// } } public static User getUserById(String id) { @@ -243,10 +433,22 @@ public static User getUserById(String id) { return user; } return null; +// try { +// JsonObject jsonObject = sendGET("resource", "User", id); +// return (User) new Gson().fromJson(jsonObject.get("object"), Class.forName("model." + jsonObject.get("className").getAsString())); +// } catch (Exception e) { +// e.printStackTrace(); +// for (User user : allUsers) { +// if (user.getId().equals(id)) +// return user; +// } +// return null; +// } } public static JsonElement getRequestById(String id) { - for (JsonElement jsonElement : allRequests) { + for (Request request : allRequests) { + JsonElement jsonElement = request.getJsonObject(); if (jsonElement.getAsJsonObject().get("id").getAsString().equals(id)) { return jsonElement; } @@ -278,6 +480,14 @@ public static Comment getCommentById(String id) { return null; } + public static Chat getChatById(String id) { + for (Chat chat : allChats) { + if (chat.getId().equals(id)) + return chat; + } + return null; + } + public static Property getPropertyById(String id) { for (Property property : allProperties) { if (property.getId().equals(id)) @@ -310,7 +520,7 @@ public static PurchaseLog getPurchaseLogById(String id) { return null; } - public static SellLog getSellLogById (String id) { + public static SellLog getSellLogById(String id) { for (SellLog log : allSellLogs) { if (log.getId().equals(id)) return log; @@ -323,6 +533,7 @@ public static User getUserByUsername(String username) { if (user.getUsername().equals(username)) return user; } + return null; } @@ -350,10 +561,14 @@ public static Property getPropertyByName(String name) { return null; } - public static ArrayList getAllPossibleManagers() { + public static ArrayList getAllPossibleManagers() { return allPossibleManagers; } + public static ArrayList getAllPossibleSupporters() { + return allPossibleSupporters; + } + public static ArrayList getAllCategories() { return allCategories; } @@ -370,7 +585,7 @@ public static ArrayList getAllUsers() { return allUsers; } - public static ArrayList getAllRequests() { + public static ArrayList getAllRequests() { return allRequests; } @@ -382,6 +597,10 @@ public static ArrayList getAllComments() { return allComments; } + public static ArrayList getAllChats() { + return allChats; + } + public static ArrayList getAllProperties() { return allProperties; } @@ -398,11 +617,19 @@ public static ArrayList getAllSellLogs() { return allSellLogs; } + public static String getServerUrl() { + return serverUrl; + } + + public static String getUserAgent() { + return USER_AGENT; + } + public static ArrayList getAllOffs() { return allOffs; } - public static void update(Object object, String id) { + public static void update(Object object, String id) throws Exception { writeObject(object, id); } @@ -413,4 +640,43 @@ public static void remove(Category category) { allCategories.remove(category); deleteObject(category, category.getId()); } + + public static void login(String username, String password) throws Exception { + String url = serverUrl + "login?" + "username=" + username + "&password=" + password; + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setDoOutput(true); + con.setInstanceFollowRedirects(false); + con.setRequestMethod("GET"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + con.setRequestProperty("charset", "utf-8"); + con.setUseCaches(false); + + int responseCode = con.getResponseCode(); + System.out.println("POST Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = convertedObject.get("token").getAsString(); + } + + public static void logout() throws Exception { + String url = serverUrl + "logout?" + "token=" + token; + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setDoOutput(true); + con.setInstanceFollowRedirects(false); + con.setRequestMethod("DELETE"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + con.setRequestProperty("charset", "utf-8"); + con.setRequestProperty("AuthToken", token); + con.setUseCaches(false); + + int responseCode = con.getResponseCode(); + System.out.println("DELETE Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = "random-customer"; + } } diff --git a/src/main/java/controller/FileGetter.java b/src/main/java/controller/FileGetter.java new file mode 100644 index 0000000..838bef7 --- /dev/null +++ b/src/main/java/controller/FileGetter.java @@ -0,0 +1,71 @@ +package controller; + +import com.google.gson.JsonObject; +import model.Product; +import model.Seller; + +import java.io.*; +import java.net.Socket; + +public class FileGetter { + + public final static int FILE_SIZE = 6022386; // file size temporary hard coded + public static int SOCKET_PORT = 13267; // you may change this + public static String SERVER = "127.0.0.1"; // localhost + // different name because i don't want to + // overwrite the one used by server... + public static String + FILE_TO_RECEIVED = "c:/temp/source-downloaded.pdf"; // you may change this, I give a + private static String SELLER_TOKEN; + private static String FILE_ADDRESS; + // should bigger than the file to be downloaded + + public static void getProduct(Product product) throws Exception { + Seller seller = product.getSellers().get(0); + FILE_ADDRESS = product.getFileAddress(); + FILE_TO_RECEIVED = "C:\\Users\\morabba\\myDownloads\\download"; + JsonObject jsonObject = Database.sendGET("p2p?seller=" + seller.getUsername()); + SOCKET_PORT = Integer.parseInt(jsonObject.get("port").getAsString()); + SERVER = jsonObject.get("ip").getAsString(); + SELLER_TOKEN = jsonObject.get("sellerToken").getAsString(); + get(); + } + + public static void get() throws IOException { + int bytesRead; + int current = 0; + FileOutputStream fos = null; + BufferedOutputStream bos = null; + Socket sock = null; + try { + sock = new Socket(SERVER, SOCKET_PORT); + System.out.println("Connecting..."); + PrintWriter clientOut = new PrintWriter(sock.getOutputStream(), true); + + clientOut.println(FILE_ADDRESS); + System.out.println("client: " + FILE_ADDRESS); + // receive file + byte[] mybytearray = new byte[FILE_SIZE]; + InputStream is = sock.getInputStream(); + fos = new FileOutputStream(FILE_TO_RECEIVED); + bos = new BufferedOutputStream(fos); + bytesRead = is.read(mybytearray, 0, mybytearray.length); + current = bytesRead; + + do { + bytesRead = is.read(mybytearray, current, (mybytearray.length - current)); + if (bytesRead >= 0) current += bytesRead; + } while (bytesRead > -1); + + bos.write(mybytearray, 0, current); + bos.flush(); + System.out.println("File " + FILE_TO_RECEIVED + + " downloaded (" + current + " bytes read)"); + } finally { + if (fos != null) fos.close(); + if (bos != null) bos.close(); + if (sock != null) sock.close(); + } + } + +} \ No newline at end of file diff --git a/src/main/java/controller/FileSender.java b/src/main/java/controller/FileSender.java new file mode 100644 index 0000000..33f8dce --- /dev/null +++ b/src/main/java/controller/FileSender.java @@ -0,0 +1,98 @@ +package controller; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicInteger; + +public class FileSender extends Thread { + private final Object lock = new Object(); + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + private AtomicInteger connectedClients = new AtomicInteger(0); + private HashMap accounts = new HashMap<>(); + + @Override + public void run() { + try { + startServer(); + } catch (Exception e) { + try { + sleep(1000); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + run(); + } + } + + private void startServer() throws Exception { + int port = 2000; + for (; port < 5000; port++) { + try { + serverSocket = new ServerSocket(port); + break; + } catch (IOException ex) { + continue; // try next port + } + } + Database.sendPOSTsellerPort(port); + new Thread(this::listen).start(); + } + + private void listen() { + while (true) { + try { + Socket client = serverSocket.accept(); + connectedClients.incrementAndGet(); + new Thread(() -> { + try { + handleClient(client); + } catch (IOException e) { + e.printStackTrace(); + } + }).start(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + private void handleClient(Socket client) throws IOException { + FileInputStream fis = null; + BufferedInputStream bis = null; + OutputStream os = null; + try { + Socket threadClient = client; + //PrintWriter clientOut = new PrintWriter(threadClient.getOutputStream(), true); + BufferedReader clientIn = new BufferedReader(new InputStreamReader(threadClient.getInputStream())); + + + ServerSocket servsock = serverSocket; + + String input = clientIn.readLine(); + input = input.replaceAll("file:", ""); + System.out.println("Server: " + input); + File myFile = new File(input); + byte[] myByteArray = new byte[(int) myFile.length()]; + fis = new FileInputStream(myFile); + bis = new BufferedInputStream(fis); + bis.read(myByteArray, 0, myByteArray.length); + os = client.getOutputStream(); + System.out.println("Sending " + input + "(" + myByteArray.length + " bytes)"); + os.write(myByteArray, 0, myByteArray.length); + os.flush(); + System.out.println("Done."); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (bis != null) bis.close(); + if (os != null) os.close(); + if (client != null) client.close(); + } + } +} \ No newline at end of file diff --git a/src/main/java/controller/ManagerController.java b/src/main/java/controller/ManagerController.java index 5405ab8..9657436 100644 --- a/src/main/java/controller/ManagerController.java +++ b/src/main/java/controller/ManagerController.java @@ -3,7 +3,6 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; -import com.google.gson.JsonObject; import model.*; import model.exception.UserNotFoundException; @@ -22,6 +21,7 @@ public ManagerController(User user, ProductController productController) { public static boolean managerExists() { for (User user : Database.getAllUsers()) { + System.out.println(user); if (user.getClass() == Manager.class) return true; } @@ -32,7 +32,7 @@ public void createDiscount(HashMap data) throws Exception { throw new Exception("got a discount code: " + data); } - public void createDiscount(Discount discount) { + public void createDiscount(Discount discount) throws Exception { Database.add(discount); } @@ -76,7 +76,7 @@ public void removeDiscount(String discountCode) { public void removeProduct(String discountCode) { } - public ArrayList viewRequests() { + public ArrayList viewRequests() { return Database.getAllRequests(); } @@ -176,7 +176,7 @@ public void editCategory(String category, HashMap fields) { // this should change into something functional for adding/removing properties } - public void createCategory(HashMap fields) { + public void createCategory(HashMap fields) throws Exception { // what to do with arguments? Database.add(new Category(fields.get("name"))); } diff --git a/src/main/java/controller/SellerController.java b/src/main/java/controller/SellerController.java index 8f2e72d..beaa100 100644 --- a/src/main/java/controller/SellerController.java +++ b/src/main/java/controller/SellerController.java @@ -84,7 +84,7 @@ public void addProduct(HashMap fields) throws Exception { Database.add(jsonElement.getAsJsonObject()); } - public void addProduct (Product product) { + public void addProduct(Product product) throws Exception { Gson request = new Gson(); JsonElement jsonElement = new JsonObject(); jsonElement.getAsJsonObject().addProperty("requestStatus", "pending"); //pending, accepted, rejected @@ -162,7 +162,7 @@ public String getOffItem(String offId, String field) throws NoSuchFieldException return res; } - public Iterable viewRequests() { + public ArrayList viewRequests() { return Database.getAllRequests(); } } \ No newline at end of file diff --git a/src/main/java/controller/UserController.java b/src/main/java/controller/UserController.java index afd21e9..7f7f6e5 100644 --- a/src/main/java/controller/UserController.java +++ b/src/main/java/controller/UserController.java @@ -1,11 +1,16 @@ package controller; +import com.google.gson.JsonObject; import model.*; import model.exception.UserNotFoundException; +import java.net.HttpURLConnection; +import java.net.URL; import java.util.HashMap; import java.util.List; +import static controller.Database.getJsonObjectFromReader; + public class UserController { protected User userLoggedOn; protected ProductController productController; @@ -19,6 +24,7 @@ public UserController(User userLoggedOn, ProductController productController) { } public void loginUser(String username, String password) throws Exception { + Database.login(username, password); User thisUser = Database.getUserByUsername(username); if (thisUser == null) throw new UserNotFoundException(); @@ -53,6 +59,15 @@ public void registerAccount(HashMap data, boolean newManagerAllo data.get("password"), Long.parseLong(data.get("credit"))); Database.add(manager); break; + case "Supporter": + if (!canBeSupporter(data.get("username"))) + throw new Exception("You can't create a supporter account"); + Supporter supporter = new Supporter(data.get("username"), + data.get("name"), data.get("surname"), data.get("email"), data.get("phoneNumber"), + data.get("password"), Long.parseLong(data.get("credit"))); + Database.add(supporter); + break; + case "Seller": Seller seller = new Seller(data.get("username"), data.get("name"), data.get("surname"), data.get("email"), data.get("phoneNumber"), @@ -113,19 +128,19 @@ private String getString(String field, User user) { } } - public void changePersonalInfo(String field, String newValue) { + public void changePersonalInfo(String field, String newValue) throws Exception { HashMap hashMap = new HashMap<>(); hashMap.put(field, newValue); changePersonalInfo(hashMap); } - public void changePersonalInfo(String username, String field, String newValue) { + public void changePersonalInfo(String username, String field, String newValue) throws Exception { HashMap hashMap = new HashMap<>(); hashMap.put(field, newValue); changePersonalInfo(username, hashMap); } - public void changePersonalInfo(String username, HashMap infoToSet) { + public void changePersonalInfo(String username, HashMap infoToSet) throws Exception { User user = Database.getUserByUsername(username); for (String info : infoToSet.keySet()) { String value = infoToSet.get(info); @@ -168,7 +183,7 @@ public void changePersonalInfo(String username, HashMap infoToSe Database.writeObject(user, user.getId()); } - public void changePersonalInfo(HashMap infoToSet) { + public void changePersonalInfo(HashMap infoToSet) throws Exception { for (String info : infoToSet.keySet()) { String value = infoToSet.get(info); switch (info) { @@ -210,7 +225,7 @@ public void changePersonalInfo(HashMap infoToSet) { Database.writeObject(userLoggedOn, userLoggedOn.getId()); } - public void addReview(String title, String text) { + public void addReview(String title, String text) throws Exception { Comment thisComment = new Comment(null, this.userLoggedOn, productController.getCurrentProduct(), title, text); @@ -225,11 +240,31 @@ public void addManager(String username) throws Exception { Database.addPossibleManager(username); } + public void addSupporter(String username) throws Exception { + User thisUser = Database.getUserByUsername(username); + if (thisUser != null) + throw new Exception("User already exists"); + Database.addPossibleSupporter(username); + } + public boolean canBeManager(String username) { - return Database.getAllPossibleManagers().contains(username); + for (PossibleManager manager : Database.getAllPossibleManagers()) { + if (manager.getUsername().equals(username)) + return true; + } + return false; } - public void logout() { + public boolean canBeSupporter(String username) { + for (PossibleSupporter supporter : Database.getAllPossibleSupporters()) { + if (supporter.getUsername().equals(username)) + return true; + } + return false; + } + + public void logout() throws Exception { + Database.logout(); userLoggedOn = CustomerController.newDefaultUser(); } @@ -248,4 +283,35 @@ public void removeProduct(String productId) throws Exception { public String getAddress() { return userLoggedOn.getAddress(); } + + protected String sendRequestToServer(String url) throws Exception { + System.out.println(url); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", Database.getUserAgent()); + int responseCode = con.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + if (convertedObject.get("ok").getAsString().equalsIgnoreCase("false")) + throw new Exception(convertedObject.get("error").getAsString()); + return convertedObject.get("reply").getAsString(); + } + + public String depositCredit(long money) throws Exception { + System.out.println("Money value " + money + " deposited"); + String url = Database.getServerUrl() + "makeTransaction" + "?username=" + userLoggedOn.getUsername() + + "&password=" + userLoggedOn.getPassword() + "&type=deposit" + "&money=" + money + "&sourceId=-1" + + "&destId=" + userLoggedOn.getBankAccountId(); + return sendRequestToServer(url); + } + + public String withdrawCredit(long money) throws Exception { + System.out.println("Money value " + money+ " withdrawn"); + String url = Database.getServerUrl() + "makeTransaction" + "?username=" + userLoggedOn.getUsername() + + "&password=" + userLoggedOn.getPassword() + "&type=withdraw" + "&money=" + money + "&sourceId=" + + userLoggedOn.getBankAccountId() + "&destId=-1"; + return sendRequestToServer(url); + } } diff --git a/src/main/java/graphics/AddCategoryPage.java b/src/main/java/graphics/AddCategoryPage.java index cee5aca..49029f5 100644 --- a/src/main/java/graphics/AddCategoryPage.java +++ b/src/main/java/graphics/AddCategoryPage.java @@ -119,7 +119,7 @@ public void newPropertyPressed(ActionEvent actionEvent) throws IOException { Main.popupStage.show(); } - public void submitPressed(ActionEvent actionEvent) throws IOException { + public void submitPressed(ActionEvent actionEvent) throws Exception { if (category.getName() == null) { category.setName(name.getText()); Database.add(category); @@ -134,7 +134,7 @@ public void submitPressed(ActionEvent actionEvent) throws IOException { Main.setMainStage("Manage Categories", "src/main/resources/fxml/ManageCategories.fxml"); } - public void addProperty(String name, String type) { + public void addProperty(String name, String type) throws Exception { Property property = new Property(); property.setNumber(type.equals("Integer")); property.setName(name); diff --git a/src/main/java/graphics/AddProductPage.java b/src/main/java/graphics/AddProductPage.java index c9fe2af..456f6b6 100644 --- a/src/main/java/graphics/AddProductPage.java +++ b/src/main/java/graphics/AddProductPage.java @@ -30,12 +30,13 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; -import java.util.HashMap; public class AddProductPage { public JFXButton selectCategoryButton; public JFXTextField quantity; public VBox mainBox; + public Label filePath; + public JFXButton fileButton; private SellerController controller; public RequiredFieldValidator requiredVal; public RegexValidator numberValid; @@ -59,6 +60,7 @@ public class AddProductPage { private String selectedCategory; private String imageUri; private String videoUri; + private String fileUri; public AddProductPage show(SellerController controller) throws IOException { System.out.println("show: " + controller); @@ -136,6 +138,17 @@ public void browseForVideo() throws MalformedURLException { } } + public void browseForFile() throws MalformedURLException { + fileChooser = new FileChooser(); + fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Files", + "*.*")); + File file = fileChooser.showOpenDialog(new Stage()); + if (file != null) { + fileUri = file.toURI().toURL().toString(); + filePath.setText(file.getAbsolutePath()); + } + } + public void loadProduct() throws Exception { FXMLLoader loader = new ProductsList().show((Seller) controller.getUser()); ProductsList list = loader.getController(); @@ -239,6 +252,7 @@ public void submitProduct() throws Exception { product.setQuantity(Integer.parseInt(quantity.getText())); product.setImageAddress(imageUri); product.setVideoAddress(videoUri); + product.setFileAddress(fileUri); for (Node child : categoryBox.getChildren()) { if (child instanceof JFXTextField) { Property property = new Property(Database.getPropertyByName(((JFXTextField) child).getPromptText())); diff --git a/src/main/java/graphics/AddSupporterMenu.java b/src/main/java/graphics/AddSupporterMenu.java new file mode 100644 index 0000000..70a89ed --- /dev/null +++ b/src/main/java/graphics/AddSupporterMenu.java @@ -0,0 +1,14 @@ +package graphics; + +import com.jfoenix.controls.JFXTextField; +import javafx.event.ActionEvent; +import main.Main; + +public class AddSupporterMenu { + public JFXTextField username; + + public void addSupporterPressed() throws Exception { + Main.controller.addSupporter(username.getText()); + Main.popupStage.close(); + } +} diff --git a/src/main/java/graphics/AdditionalInfo.java b/src/main/java/graphics/AdditionalInfo.java index 9234b28..9b150b2 100644 --- a/src/main/java/graphics/AdditionalInfo.java +++ b/src/main/java/graphics/AdditionalInfo.java @@ -11,7 +11,6 @@ import main.Main; import java.io.File; -import java.net.MalformedURLException; import java.util.HashMap; public class AdditionalInfo { @@ -23,7 +22,7 @@ public class AdditionalInfo { private FileChooser fileChooser = new FileChooser(); - public void submitButtonPressed(ActionEvent actionEvent) { + public void submitButtonPressed(ActionEvent actionEvent) throws Exception { HashMap data = new HashMap<>(); data.put("email", email.getText()); data.put("gender", gender.getValue().toString()); @@ -33,7 +32,7 @@ public void submitButtonPressed(ActionEvent actionEvent) { Main.popupStage.close(); } - public void chooseProfilePicture(ActionEvent actionEvent) throws MalformedURLException { + public void chooseProfilePicture(ActionEvent actionEvent) throws Exception { fileChooser.setTitle("Choose new profile picture..."); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")); File selectedFile = fileChooser.showOpenDialog(Main.popupStage); diff --git a/src/main/java/graphics/ChatBox.java b/src/main/java/graphics/ChatBox.java new file mode 100644 index 0000000..ad67868 --- /dev/null +++ b/src/main/java/graphics/ChatBox.java @@ -0,0 +1,107 @@ +package graphics; + +import controller.Database; +import javafx.scene.control.Label; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TextArea; +import javafx.scene.input.KeyCode; +import javafx.scene.layout.VBox; +import main.Main; +import model.Chat; +import model.ChatMessage; + +import java.util.Objects; + +public class ChatBox extends VBox { + private Chat chat; + + ScrollPane scrollPane; + VBox messagesBox; + TextArea textArea; + + + public void setChat(Chat chat) { + this.chat = chat; + + textArea.setDisable(true); + messagesBox.getChildren().clear(); + + if (chat == null) + return; + + textArea.setDisable(false); + + for (ChatMessage message : chat.getMessages()) { + addMessageToBox(message); + } + + StringBuilder members = new StringBuilder(); + for (String username : chat.getUsers()) { + members.append(username).append(", "); + } + + messagesBox.getChildren().add(new Label("Chat members:")); + messagesBox.getChildren().add(new Label(members.substring(0, members.length() - 2))); + + } + + public void updateChat() { + System.out.println("setting chat messages..."); + if (getChat() != null) + chat = Database.getChatById(getChat().getId()); + setChat(chat); + } + + public ChatBox() { + this.minWidth(400); + this.maxWidth(400); + messagesBox = new VBox(); + messagesBox.setPrefWidth(390); + messagesBox.setStyle("\n" + + " -fx-padding: 10px;\n" + + " -fx-spacing: 10px; -fx-alignment: top-center"); + + scrollPane = new ScrollPane(messagesBox); + scrollPane.setPrefHeight(250); + + textArea = new TextArea(); + textArea.setDisable(true); + textArea.setPromptText("Press enter to send..."); + textArea.setPrefHeight(50); + + this.getChildren().addAll(textArea, scrollPane); + + + textArea.setOnKeyPressed(event -> { + if (event.getCode() == KeyCode.ENTER) { + event.consume(); + if (event.isShiftDown()) { + textArea.appendText(System.getProperty("line.separator")); + } else { + + // get chat from server + chat = Database.getChatById(chat.getId()); + assert chat != null; + // add message to chat + chat.addMessage(new ChatMessage(Main.controller.getUser().getId(), textArea.getText())); + // write chat into server + try { + Database.update(chat, chat.getId()); + } catch (Exception e) { + e.printStackTrace(); + } + this.updateChat(); + textArea.setText(""); + } + } + }); + } + + private void addMessageToBox(ChatMessage message) { + messagesBox.getChildren().add(0, new MessagePane(message)); + } + + public Chat getChat() { + return chat; + } +} diff --git a/src/main/java/graphics/LoginMenu.java b/src/main/java/graphics/LoginMenu.java index 1319f8d..1d1f628 100644 --- a/src/main/java/graphics/LoginMenu.java +++ b/src/main/java/graphics/LoginMenu.java @@ -3,6 +3,7 @@ import com.jfoenix.controls.JFXPasswordField; import com.jfoenix.controls.JFXTextField; import controller.CustomerController; +import controller.FileSender; import controller.ManagerController; import controller.SellerController; import javafx.event.ActionEvent; @@ -29,6 +30,7 @@ public void SignInPressed(ActionEvent actionEvent) throws Exception { } if (Main.controller.getUser().getClass() == Seller.class) { Main.sellerController = new SellerController(Main.controller.getUser(), Main.productController); + new FileSender().start(); } if (Main.controller.getUser().getClass() == Manager.class) { Main.managerController = new ManagerController(Main.controller.getUser(), Main.productController); diff --git a/src/main/java/graphics/MainMenu.java b/src/main/java/graphics/MainMenu.java index 3e98969..db04feb 100644 --- a/src/main/java/graphics/MainMenu.java +++ b/src/main/java/graphics/MainMenu.java @@ -7,13 +7,14 @@ import javafx.stage.Modality; import javafx.stage.Stage; import main.Main; +import model.exception.DefaultUser; import java.io.File; import java.io.IOException; import java.net.URL; public class MainMenu { - public void va(ActionEvent actionEvent) { + public void va() { System.out.println("YAAY"); } @@ -21,9 +22,9 @@ public void initialize() { SoundPlayer.playInfinite("paganini.wav"); } - public void profileButtonPressed(ActionEvent actionEvent) throws IOException { + public void profileButtonPressed() throws IOException { System.out.println(Main.controller.getUser()); - if (Main.controller.getUser().getFullName().equals("Anonymous User ")) { + if (Main.controller.getUser() instanceof DefaultUser) { URL url = new File("src/main/resources/fxml/LoginMenu.fxml").toURI().toURL(); Parent root = FXMLLoader.load(url); Main.popupStage = new Stage(); @@ -36,15 +37,18 @@ public void profileButtonPressed(ActionEvent actionEvent) throws IOException { SoundPlayer.stopBackground(); String fxmlPath; switch (Main.controller.getPersonalInfo("type")) { - case "customer": - fxmlPath = "src/main/resources/fxml/Profile.fxml"; - break; +// case "customer": +// fxmlPath = "src/main/resources/fxml/Profile.fxml"; +// break; case "seller": fxmlPath = "src/main/resources/fxml/SellerPage.fxml"; break; case "manager": fxmlPath = "src/main/resources/fxml/ManagerPage.fxml"; - System.out.println("va"); + break; + case "customer": + case "supporter": + fxmlPath = "src/main/resources/fxml/SupporterPage.fxml"; break; default: throw new IllegalStateException("Unexpected value: " + Main.controller.getPersonalInfo("type")); @@ -54,7 +58,7 @@ public void profileButtonPressed(ActionEvent actionEvent) throws IOException { } } - public void productsButtonPressed(ActionEvent actionEvent) throws IOException { + public void productsButtonPressed() { SoundPlayer.stopBackground(); System.out.println("Product section"); Main.setMainStage("Products", "src/main/resources/fxml/ProductsPage.fxml"); diff --git a/src/main/java/graphics/ManagerPage.java b/src/main/java/graphics/ManagerPage.java index 2b96748..3511282 100644 --- a/src/main/java/graphics/ManagerPage.java +++ b/src/main/java/graphics/ManagerPage.java @@ -1,6 +1,5 @@ package graphics; -import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; @@ -26,18 +25,18 @@ public void initialize() { backgroundMediaView.mediaPlayerProperty().set(mediaPlayer); } - public void profilePageButtonPressed(ActionEvent actionEvent) throws IOException { + public void profilePageButtonPressed() { backgroundMediaView.getMediaPlayer().stop(); Main.setMainStage("Profile Page", "src/main/resources/fxml/Profile.fxml"); } - public void manageRequestsButtonPressed(ActionEvent actionEvent) throws IOException { + public void manageRequestsButtonPressed() { backgroundMediaView.getMediaPlayer().stop(); Main.setMainStage("Manage Requests", "src/main/resources/fxml/ManagerRequestsPage.fxml"); } - public void addManagerButtonPressed(ActionEvent actionEvent) throws IOException { + public void addManagerButtonPressed() throws IOException { backgroundMediaView.getMediaPlayer().stop(); URL url = new File("src/main/resources/fxml/AddManagerMenu.fxml").toURI().toURL(); Parent root = FXMLLoader.load(url); @@ -49,23 +48,47 @@ public void addManagerButtonPressed(ActionEvent actionEvent) throws IOException Main.popupStage.show(); } - public void addDiscountButtonPressed(ActionEvent actionEvent) throws IOException { + public void addSupporterButtonPressed() throws IOException { + backgroundMediaView.getMediaPlayer().stop(); + URL url = new File("src/main/resources/fxml/AddSupporterMenu.fxml").toURI().toURL(); + Parent root = FXMLLoader.load(url); + Main.popupStage = new Stage(); + Main.popupStage.setTitle("Add new supporter"); + Main.popupStage.setScene(new Scene(root, 250, 250)); + Main.popupStage.initModality(Modality.WINDOW_MODAL); + Main.popupStage.initOwner(Main.mainStage); + Main.popupStage.show(); + } + + public void addDiscountButtonPressed() throws IOException { backgroundMediaView.getMediaPlayer().stop(); System.out.println("Manager Controller: " + Main.managerController); new ManageDiscountsPage().show(null); } - public void manageUsersButtonPressed(ActionEvent actionEvent) throws IOException { + public void manageUsersButtonPressed() { backgroundMediaView.getMediaPlayer().stop(); Main.setMainStage("Manage Users", "src/main/resources/fxml/UserViewer.fxml"); } - public void removeProductPressed(ActionEvent actionEvent) throws IOException { + public void removeProductPressed() throws IOException { SellerPage.showRemovePage(backgroundMediaView); } - public void manageCategoriesButtonPressed(ActionEvent actionEvent) throws IOException { + public void manageCategoriesButtonPressed() { backgroundMediaView.getMediaPlayer().stop(); Main.setMainStage("Manage Categories", "src/main/resources/fxml/ManageCategories.fxml"); } + + public void setConstantsPressed() throws IOException { + backgroundMediaView.getMediaPlayer().stop(); + URL url = new File("src/main/resources/fxml/SetConstantsMenu.fxml").toURI().toURL(); + Parent root = FXMLLoader.load(url); + Main.popupStage = new Stage(); + Main.popupStage.setTitle("Set constants"); + Main.popupStage.setScene(new Scene(root, 250, 350)); + Main.popupStage.initModality(Modality.WINDOW_MODAL); + Main.popupStage.initOwner(Main.mainStage); + Main.popupStage.show(); + } } diff --git a/src/main/java/graphics/ManagerRequestsPage.java b/src/main/java/graphics/ManagerRequestsPage.java index 6cab247..090c60e 100644 --- a/src/main/java/graphics/ManagerRequestsPage.java +++ b/src/main/java/graphics/ManagerRequestsPage.java @@ -17,6 +17,7 @@ import javafx.util.Callback; import main.Main; import model.Product; +import model.Request; import java.io.File; @@ -34,7 +35,8 @@ public void initialize() { TreeItem removeProduct = new TreeItem<>(new RequestRow("remove product")); TreeItem ads = new TreeItem<>(new RequestRow("advertisement")); - for (JsonElement json : (Main.managerController).viewRequests()) { + for (Request request : (Main.managerController).viewRequests()) { + JsonElement json = request.getJsonObject(); if (json.getAsJsonObject().get("requestStatus").getAsString().equals("pending")) { switch (json.getAsJsonObject().get("request-type").getAsString()) { case "add off": diff --git a/src/main/java/graphics/MessagePane.java b/src/main/java/graphics/MessagePane.java new file mode 100644 index 0000000..00cc0f3 --- /dev/null +++ b/src/main/java/graphics/MessagePane.java @@ -0,0 +1,63 @@ +package graphics; + +import javafx.geometry.Insets; +import javafx.geometry.Pos; +import javafx.scene.control.Hyperlink; +import javafx.scene.control.Label; +import javafx.scene.control.Separator; +import javafx.scene.image.ImageView; +import javafx.scene.layout.HBox; +import javafx.scene.layout.VBox; +import main.Main; +import model.ChatMessage; +import model.User; +import model.exception.DefaultUser; + +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; + +public class MessagePane extends HBox { + + int width = 400 - 30; + + public MessagePane(ChatMessage message) { + boolean isSender = message.getSenderId().equals(Main.controller.getUser().getId()); + + this.setPrefWidth(width); + + VBox textBox = new VBox(); + VBox voidBox = new VBox(); + + textBox.setPrefWidth(width); + textBox.setPadding(new Insets(10)); + textBox.setAlignment(Pos.CENTER_LEFT); + + voidBox.setMinWidth(50); + voidBox.setMaxWidth(50); + + //User user = new DefaultUser(); + //ImageView userImage = new ImageView(user.getProfilePictureAddress()); + + + Label messageText = new Label(message.getText()); + messageText.setWrapText(true); + + textBox.getChildren().addAll(messageText); + + + String textStyle = "-fx-border-radius: 5;\n" + + "-fx-border-width: 1;\n" + + "-fx-border-color: #BDBDBD;\n" + + "-fx-spacing: 10px;\n" + + "-fx-alignment: center-left;"; + + if (isSender) { + textStyle += "-fx-background-color: #EFFDDE"; + this.getChildren().addAll(voidBox, textBox); + } else { + textStyle += "-fx-background-color: white"; + this.getChildren().addAll(textBox, voidBox); + } + textBox.setStyle(textStyle); + } +} diff --git a/src/main/java/graphics/PaymentPage.java b/src/main/java/graphics/PaymentPage.java index 3b2c983..77939e6 100644 --- a/src/main/java/graphics/PaymentPage.java +++ b/src/main/java/graphics/PaymentPage.java @@ -1,6 +1,7 @@ package graphics; import com.jfoenix.controls.JFXButton; +import com.jfoenix.controls.JFXRadioButton; import com.jfoenix.controls.JFXTextArea; import com.jfoenix.controls.JFXTextField; import controller.CustomerController; @@ -13,6 +14,8 @@ import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; +import javafx.scene.control.ToggleGroup; +import javafx.scene.paint.Color; import javafx.stage.Modality; import javafx.stage.Stage; import main.Main; @@ -31,6 +34,10 @@ public class PaymentPage { public Label totalPriceLabel; public JFXButton payButton; private CustomerController controller; + public JFXRadioButton bankButton; + public JFXRadioButton walletButton; + private ToggleGroup radioGroup = new ToggleGroup(); + private String paymentMethod = "e-wallet"; public void show(CustomerController controller) throws Exception { URL url = new File("src/main/resources/fxml/PaymentPage.fxml").toURI().toURL(); @@ -43,6 +50,14 @@ public void show(CustomerController controller) throws Exception { Main.popupStage.show(); ((PaymentPage)fxmlLoader.getController()).refresh(); ((PaymentPage) fxmlLoader.getController()).checkAddress(); + ((PaymentPage) fxmlLoader.getController()).toggleButtons(); + } + + private void toggleButtons() { + walletButton.setToggleGroup(radioGroup); + bankButton.setToggleGroup(radioGroup); + bankButton.setSelectedColor(Color.rgb(177, 66, 255)); + walletButton.setSelectedColor(Color.rgb(177, 66, 255)); } private void checkAddress() throws Exception { @@ -85,7 +100,7 @@ private void refresh() { } public void finishPayment(ActionEvent actionEvent) throws Exception { - long totalPrice = controller.purchase(); + long totalPrice = controller.purchase(paymentMethod); Discount gift; if (totalPrice >= 5100 && totalPrice <= 10000) { gift = Discount.getGiftDiscount(controller.getCustomerLoggedOn(), (int) ((totalPrice - 5000)/100)); @@ -108,4 +123,8 @@ private void showGiftMessage(Discount discount) { "Code: " + discount.getCode()); message.showAndWait(); } + + public void updatePaymentMethod(ActionEvent actionEvent) { + paymentMethod = ((JFXRadioButton)radioGroup.getSelectedToggle()).getText(); + } } diff --git a/src/main/java/graphics/ProductPage.java b/src/main/java/graphics/ProductPage.java index 706f653..ed27f13 100644 --- a/src/main/java/graphics/ProductPage.java +++ b/src/main/java/graphics/ProductPage.java @@ -2,15 +2,16 @@ import com.jfoenix.controls.JFXTextField; import controller.Database; +import controller.FileGetter; import controller.ProductController; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.geometry.Pos; -import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; +import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; @@ -20,7 +21,6 @@ import model.*; import model.exception.DefaultUser; -import javax.security.auth.callback.LanguageCallback; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; @@ -31,6 +31,7 @@ public class ProductPage { public HBox similarBox; + public Button downloadButton; private Product product; public VBox mediaBox; @@ -228,6 +229,10 @@ public void copyPressed() { compareArea.getChildren().add(new Label("product id copied into clipboard")); } + public void downloadPressed(ActionEvent actionEvent) throws Exception { + FileGetter.getProduct(product); + } + public class CommentPane extends HBox { int leftSize = 80; int rightSize = 420; diff --git a/src/main/java/graphics/ProfilePage.java b/src/main/java/graphics/ProfilePage.java index 3743db2..cbbc001 100644 --- a/src/main/java/graphics/ProfilePage.java +++ b/src/main/java/graphics/ProfilePage.java @@ -3,8 +3,6 @@ import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXDatePicker; -import controller.CustomerController; -import controller.SellerController; import javafx.event.ActionEvent; import javafx.scene.control.TextInputControl; import javafx.scene.image.Image; @@ -15,7 +13,6 @@ import java.io.File; import java.io.IOException; -import java.net.MalformedURLException; import java.time.LocalDate; public class ProfilePage { @@ -79,7 +76,7 @@ public void initialize() { } } - public void chooseProfilePicture(ActionEvent actionEvent) throws MalformedURLException { + public void chooseProfilePicture(ActionEvent actionEvent) throws Exception { fileChooser.setTitle("Choose new profile picture..."); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")); File selectedFile = fileChooser.showOpenDialog(Main.popupStage); @@ -92,7 +89,7 @@ public void chooseProfilePicture(ActionEvent actionEvent) throws MalformedURLExc } } - public void propertyChanged(ActionEvent actionEvent) { + public void propertyChanged(ActionEvent actionEvent) throws Exception { switch (actionEvent.getSource().getClass().getName()) { case "com.jfoenix.controls.JFXDatePicker": System.out.println(((JFXDatePicker) actionEvent.getSource()).getValue().toString()); @@ -104,10 +101,32 @@ public void propertyChanged(ActionEvent actionEvent) { break; default: System.out.println(((TextInputControl) actionEvent.getSource()).getPromptText() + ".setText(Main.controller.getPersonalInfo(\"" + ((TextInputControl) actionEvent.getSource()).getPromptText() + "\");"); + if (((TextInputControl) actionEvent.getSource()).getPromptText().equals("credit") ) { + try { + makeTransaction(Long.parseLong(((TextInputControl) actionEvent.getSource()).getText())); + }catch (Exception e) { + ((TextInputControl) actionEvent.getSource()). + setText(String.valueOf(Main.controller.getUser().getCredit())); + throw e; + } + } Main.controller.changePersonalInfo(user, ((TextInputControl) actionEvent.getSource()).getPromptText(), ((TextInputControl) actionEvent.getSource()).getText()); } } + private void makeTransaction(long newValue) throws Exception { + long oldValue = Main.controller.getUser().getCredit(); + System.out.println("OldVal= " + oldValue); + System.out.println("newVal= " + newValue); + if (newValue < oldValue) { + String result = Main.controller.depositCredit(oldValue - newValue); + System.out.println(result); + }else if (newValue > oldValue) { + String result = Main.controller.withdrawCredit(newValue - oldValue); + System.out.println(result); + } + } + public void viewDiscountsPressed(ActionEvent actionEvent) throws IOException { ManageDiscountsPage.show(Main.controller.getUser()); } diff --git a/src/main/java/graphics/PropertyPage.java b/src/main/java/graphics/PropertyPage.java index c5b54c8..1c09600 100644 --- a/src/main/java/graphics/PropertyPage.java +++ b/src/main/java/graphics/PropertyPage.java @@ -11,7 +11,7 @@ public class PropertyPage { public AddCategoryPage categoryPage; - public void submitPressed(ActionEvent actionEvent) { + public void submitPressed(ActionEvent actionEvent) throws Exception { categoryPage.addProperty(name.getText(), type.getValue().toString()); Main.popupStage.close(); } diff --git a/src/main/java/graphics/RegisterMenu.java b/src/main/java/graphics/RegisterMenu.java index 8e036c7..5e1d28a 100644 --- a/src/main/java/graphics/RegisterMenu.java +++ b/src/main/java/graphics/RegisterMenu.java @@ -5,7 +5,6 @@ import com.jfoenix.controls.JFXTextArea; import com.jfoenix.controls.JFXTextField; import controller.ManagerController; -import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; @@ -17,7 +16,7 @@ import java.util.HashMap; public class RegisterMenu { - public JFXComboBox accountType; + public JFXComboBox accountType; public JFXTextField firstName; public JFXTextField lastName; public JFXTextField phoneNumber; @@ -30,7 +29,7 @@ public class RegisterMenu { public JFXTextArea companyInfo; - public void registerPressed(ActionEvent actionEvent) throws Exception { + public void registerPressed() throws Exception { registerAccount(); URL url = new File("src/main/resources/fxml/LoginMenu.fxml").toURI().toURL(); Parent root = FXMLLoader.load(url); @@ -63,7 +62,7 @@ private void registerAccount() throws Exception { throw (new Exception(errorText)); } HashMap data = new HashMap<>(); - data.put("type", accountType.getValue().toString()); + data.put("type", accountType.getValue()); data.put("name", firstName.getText()); data.put("surname", lastName.getText()); data.put("phoneNumber", phoneNumber.getText()); @@ -73,7 +72,7 @@ private void registerAccount() throws Exception { data.put("companyInfo", companyInfo.getText()); data.put("credit", "0"); - if (!ManagerController.managerExists() && !accountType.getValue().toString().equals("Manager")) { + if (!ManagerController.managerExists() && !accountType.getValue().equals("Manager")) { throw (new Exception("Please register a manager first")); } if (Main.controller.canBeManager(username.getText())) { @@ -83,29 +82,29 @@ private void registerAccount() throws Exception { Main.controller.registerAccount(data, false); } - public void additionalInfoPressed(ActionEvent actionEvent) throws Exception { + public void additionalInfoPressed() throws Exception { registerAccount(); URL url = new File("src/main/resources/fxml/AdditionalInfo.fxml").toURI().toURL(); Parent root = FXMLLoader.load(url); Main.popupStage.setScene(new Scene(root, 300, 400)); } - public void accountTypeChanged(ActionEvent actionEvent) { + public void accountTypeChanged() { System.out.println("called"); System.out.println(); - if (accountType.getValue().toString().equals("Seller")) { + if (accountType.getValue().equals("Seller")) { sellerBox.setManaged(true); sellerBox.setVisible(true); managerBox.setManaged(false); managerBox.setVisible(false); } - if (accountType.getValue().toString().equals("Manager")) { + if (accountType.getValue().equals("Manager")) { sellerBox.setManaged(false); sellerBox.setVisible(false); managerBox.setManaged(true); managerBox.setVisible(true); } - if (accountType.getValue().toString().equals("Customer")) { + if (accountType.getValue().equals("Supporter") || accountType.getValue().equals("Customer")) { sellerBox.setManaged(false); sellerBox.setVisible(false); managerBox.setManaged(false); diff --git a/src/main/java/graphics/SellerRequestsPage.java b/src/main/java/graphics/SellerRequestsPage.java index 1069092..e5d97e9 100644 --- a/src/main/java/graphics/SellerRequestsPage.java +++ b/src/main/java/graphics/SellerRequestsPage.java @@ -7,6 +7,7 @@ import javafx.scene.control.cell.TreeItemPropertyValueFactory; import javafx.scene.layout.VBox; import main.Main; +import model.Request; public class SellerRequestsPage { public VBox mainPane; @@ -22,7 +23,8 @@ public void initialize() { TreeItem removeProduct = new TreeItem<>(new RequestRow("remove product")); TreeItem ads = new TreeItem<>(new RequestRow("advertisement")); - for (JsonElement json : Main.sellerController.viewRequests()) { + for (Request request : Main.sellerController.viewRequests()) { + JsonElement json = request.getJsonObject(); if (!json.getAsJsonObject().get("owner").getAsString().equals(Main.controller.getUser().getId())) { continue; } diff --git a/src/main/java/graphics/SetConstantsMenu.java b/src/main/java/graphics/SetConstantsMenu.java new file mode 100644 index 0000000..ce7e159 --- /dev/null +++ b/src/main/java/graphics/SetConstantsMenu.java @@ -0,0 +1,14 @@ +package graphics; + +import com.jfoenix.controls.JFXTextField; +import controller.Database; +import javafx.event.ActionEvent; + +public class SetConstantsMenu { + public JFXTextField wage; + public JFXTextField minimumAmount; + + public void setConstantsPressed(ActionEvent actionEvent) throws Exception { + Database.sendGET("constant?wage=" + wage.getText() + "&minimumCredit=" + minimumAmount.getText()); + } +} diff --git a/src/main/java/graphics/SupportArea.java b/src/main/java/graphics/SupportArea.java new file mode 100644 index 0000000..78c7bfd --- /dev/null +++ b/src/main/java/graphics/SupportArea.java @@ -0,0 +1,92 @@ +package graphics; + +import com.jfoenix.controls.JFXButton; +import controller.Database; +import javafx.scene.control.Hyperlink; +import javafx.scene.layout.HBox; +import javafx.scene.layout.VBox; +import main.Main; +import model.Chat; +import model.Supporter; +import model.User; + +import javax.xml.crypto.Data; +import java.util.ArrayList; +import java.util.Objects; + +public class SupportArea { + public VBox onlineBox; + public ChatBox chatBox; + public HBox chatListBox; + + ArrayList chatList = new ArrayList<>(); + + public void initialize() { + System.out.println("initializing..."); + try { + ArrayList users; + users = Database.getOnlineUsers(); + + onlineBox.getChildren().clear(); + for (String userId : users) { + User user = Database.getUserById(userId); + if (user instanceof Supporter) { + Hyperlink link = new Hyperlink(user.getUsername()); + onlineBox.getChildren().add(link); + + link.setOnAction(event -> { + if (Main.controller.getUser().getType().equals("supporter")) + return; + + Chat chat = new Chat(); + + // add customer and supporter to chat members + chat.addUser(Main.controller.getUser().getUsername()); + chat.addUser(Objects.requireNonNull(Database.getUserById(userId)).getUsername()); + + try { + Database.add(chat); + chatList.add(chat.getId()); + updateChatBox(); + chatBox.setChat(chat); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + } + + chatList = new ArrayList<>(); + + for (Chat chat : Database.getAllChats()) { + if (chat.hasUser(Main.controller.getUser().getUsername())) { + chatList.add(chat.getId()); + } + } + + updateChatBox(); + + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Cannot get online users"); + } + } + + private void updateChatBox() { + chatListBox.getChildren().clear(); + for (int i = 0; i < chatList.size(); i++) { + JFXButton button = new JFXButton("Chat #" + (i + 1)); + int finalI = i; + button.setOnMouseClicked(event -> chatBox.setChat(Database.getChatById(chatList.get(finalI)))); + button.getStyleClass().add("chatButton"); + chatListBox.getChildren().add(button); + } + } + + public void reloadPressed() { + System.out.println("reloading..."); + initialize(); + chatBox.updateChat(); + //chatBox.setChat(chatBox.getChat()); + } +} diff --git a/src/main/java/graphics/SupporterPage.java b/src/main/java/graphics/SupporterPage.java new file mode 100644 index 0000000..dd7df78 --- /dev/null +++ b/src/main/java/graphics/SupporterPage.java @@ -0,0 +1,34 @@ +package graphics; + +import javafx.event.ActionEvent; +import javafx.scene.media.Media; +import javafx.scene.media.MediaPlayer; +import javafx.scene.media.MediaView; +import main.Main; + +import java.io.File; +import java.io.IOException; + +public class SupporterPage { + + public MediaView backgroundMediaView; + + public void initialize() { + MediaPlayer mediaPlayer = new MediaPlayer(new Media(new File("src/main/resources/video/chorus-video.mp4").toURI().toString())); + mediaPlayer.setAutoPlay(true); + mediaPlayer.cycleCountProperty().set(Integer.MAX_VALUE); + backgroundMediaView.mediaPlayerProperty().set(mediaPlayer); + backgroundMediaView.setFitWidth(Main.mainStage.getWidth()); + backgroundMediaView.setPreserveRatio(true); + } + + public void profilePageButtonPressed() { + backgroundMediaView.getMediaPlayer().stop(); + Main.setMainStage("Profile", "src/main/resources/fxml/Profile.fxml"); + } + + public void supportPressed() { + backgroundMediaView.getMediaPlayer().stop(); + Main.setMainStage("Support Area", "src/main/resources/fxml/SupportArea.fxml"); + } +} diff --git a/src/main/java/graphics/UserRow.java b/src/main/java/graphics/UserRow.java index 93a858e..0fccdee 100644 --- a/src/main/java/graphics/UserRow.java +++ b/src/main/java/graphics/UserRow.java @@ -10,6 +10,7 @@ public class UserRow extends RecursiveTreeObject { private StringProperty username = new SimpleStringProperty(); private StringProperty firstName = new SimpleStringProperty(); private StringProperty surname = new SimpleStringProperty(); + private StringProperty id = new SimpleStringProperty(); public UserRow() { @@ -23,6 +24,7 @@ public UserRow(User user) { username.setValue(user.getUsername()); firstName.setValue(user.getFirstName()); surname.setValue(user.getSurname()); + id.setValue(user.getId()); } public StringProperty usernameProperty() { @@ -37,6 +39,18 @@ public void setUsername(String username) { this.username.set(username); } + public StringProperty idProperty() { + return id; + } + + public String getId() { + return id.get(); + } + + public void setId(String id) { + this.id.set(id); + } + public StringProperty firstNameProperty() { return firstName; } diff --git a/src/main/java/graphics/UserViewer.java b/src/main/java/graphics/UserViewer.java index 4991872..cd54586 100644 --- a/src/main/java/graphics/UserViewer.java +++ b/src/main/java/graphics/UserViewer.java @@ -1,7 +1,11 @@ package graphics; +import com.fasterxml.jackson.databind.util.ISO8601Utils; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXTreeTableView; +import controller.Database; +import javafx.beans.property.SimpleStringProperty; +import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; @@ -19,6 +23,7 @@ import model.User; import java.io.File; +import java.util.ArrayList; public class UserViewer { public VBox mainPane; @@ -29,6 +34,7 @@ public void initialize() { treeTableView = new JFXTreeTableView(); TreeItem customers = new TreeItem<>(new UserRow("customers")); TreeItem sellers = new TreeItem<>(new UserRow("sellers")); + TreeItem supporters = new TreeItem<>(new UserRow("supporters")); TreeItem managers = new TreeItem<>(new UserRow("managers")); for (User user : Main.controller.getAllUsers()) { @@ -39,6 +45,9 @@ public void initialize() { case "seller": sellers.getChildren().add(new TreeItem<>(new UserRow(user))); break; + case "supporter": + supporters.getChildren().add(new TreeItem<>(new UserRow(user))); + break; case "manager": managers.getChildren().add(new TreeItem<>(new UserRow(user))); break; @@ -47,21 +56,40 @@ public void initialize() { TreeTableColumn columnUsername = new TreeTableColumn<>("Username"); TreeTableColumn columnFirstName = new TreeTableColumn<>("First name"); TreeTableColumn columnSurname = new TreeTableColumn<>("Sur name"); + TreeTableColumn columnStatus = new TreeTableColumn<>("Status"); columnUsername.setCellValueFactory(new TreeItemPropertyValueFactory<>("username")); columnFirstName.setCellValueFactory(new TreeItemPropertyValueFactory<>("firstName")); columnSurname.setCellValueFactory(new TreeItemPropertyValueFactory<>("surname")); + ArrayList onlineUsers = Database.getOnlineUsers(); + + for (String user : onlineUsers) { + System.out.println(user); + } + + columnStatus.setCellValueFactory(dataFeatures -> { + TreeItem item = dataFeatures.getValue(); + UserRow person = item.getValue(); + + if (person.getId() == null) + return new SimpleStringProperty(); + + return new SimpleStringProperty(onlineUsers.contains(person.getId()) ? "ONLINE" : "offline"); + }); + columnUsername.setPrefWidth(125); columnFirstName.setPrefWidth(125); columnSurname.setPrefWidth(125); + columnStatus.setPrefWidth(75); treeTableView.getColumns().add(columnUsername); treeTableView.getColumns().add(columnFirstName); treeTableView.getColumns().add(columnSurname); + treeTableView.getColumns().add(columnStatus); TreeItem users = new TreeItem<>(new UserRow("users")); - users.getChildren().addAll(customers, sellers, managers); + users.getChildren().addAll(customers, sellers, supporters, managers); treeTableView.setRoot(users); addButtonToTable(); diff --git a/src/main/java/main/Main.java b/src/main/java/main/Main.java index 325bb8d..d17bc87 100644 --- a/src/main/java/main/Main.java +++ b/src/main/java/main/Main.java @@ -1,8 +1,6 @@ package main; import controller.*; -import javafx.animation.KeyFrame; -import javafx.animation.Timeline; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; @@ -11,10 +9,7 @@ import javafx.scene.control.Alert; import javafx.stage.Modality; import javafx.stage.Stage; -import javafx.util.Duration; import model.Customer; -import model.Discount; -import model.Seller; import view.Menu; import view.userstuff.RegisterLoginMenu; @@ -23,8 +18,6 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; -import java.time.LocalDateTime; -import java.util.Random; import java.util.Stack; public class Main extends Application { @@ -35,60 +28,32 @@ public class Main extends Application { public static ManagerController managerController; public static CustomerController customerController; public static ProductController productController; - private static Stack sceneStack = new Stack<>(); + private static final Stack sceneStack = new Stack<>(); public Main() { } public static void main(String[] args) { - Database.loadAllData(); + try { + Database.loadAllData(); + } catch (Exception ignore) { + } controller = new UserController(null, Menu.productController); customerController = new CustomerController((Customer) controller.getUser(), Menu.productController); productController = new ProductController(); - makeRandomDiscounts(); - launch(args); new RegisterLoginMenu(new UserController(null, Menu.productController)); } - private static void makeRandomDiscounts() { - Timeline workStuff = new Timeline(); - workStuff.setCycleCount(Timeline.INDEFINITE); - Random random = new Random(); - - KeyFrame kf = new KeyFrame( - Duration.seconds(5), // 1 FPS - ae -> { - if (random.nextDouble() < 0.1) { - int userIndex = random.nextInt(Database.getAllUsers().size()); - Discount discount = new Discount(); - discount.setCode(Discount.generateRandomCode()); - discount.setDiscountPercent(random.nextInt(50) + 1); - discount.setStartTime(LocalDateTime.now()); - discount.setFinishTime(LocalDateTime.now().plusDays(1)); - discount.setMaximumAmount(random.nextInt(11) + 10); - discount.setRepetitionNumber(1); - discount.addUser(Database.getAllUsers().get(userIndex)); - System.out.println(Database.getAllUsers().get(userIndex).getUsername()); - Database.add(discount); - } - }); - - workStuff.getKeyFrames().add(kf); - workStuff.play(); - } - private static void showError(Thread t, Throwable e) { System.err.println("***Default exception handler***"); e.printStackTrace(); if (Platform.isFxApplicationThread()) { showErrorDialog(e); - System.err.println("An unexpected error occurred in " + t); - } else { - System.err.println("An unexpected error occurred in " + t); } + System.err.println("An unexpected error occurred in " + t); } public static void showErrorDialog(Throwable e) { @@ -173,7 +138,7 @@ public static void setPopupStageSize(double width, double height) { } @Override - public void start(Stage primaryStage) throws Exception { + public void start(Stage primaryStage) { Thread.setDefaultUncaughtExceptionHandler(Main::showError); // Database.addProductToAds(Database.getProductById("111388d0-ac14-4a24-b54f-fda183df6c2d")); // Database.addProductToAds(Database.getProductById("efe8e6bf-4b3c-4699-b3cf-16c6fd89c483")); @@ -181,4 +146,10 @@ public void start(Stage primaryStage) throws Exception { Main.setMainStage("", "src/main/resources/fxml/MainMenu.fxml"); primaryStage.show(); } + + @Override + public void stop() throws Exception { + if (Main.controller.getUser() != null) + Database.logout(); + } } diff --git a/src/main/java/model/BaseModel.java b/src/main/java/model/BaseModel.java new file mode 100644 index 0000000..9ff7fab --- /dev/null +++ b/src/main/java/model/BaseModel.java @@ -0,0 +1,5 @@ +package model; + +public interface BaseModel { + String getId(); +} diff --git a/src/main/java/model/Category.java b/src/main/java/model/Category.java index 64e6799..1e45b2a 100644 --- a/src/main/java/model/Category.java +++ b/src/main/java/model/Category.java @@ -5,7 +5,7 @@ import java.util.ArrayList; import java.util.UUID; -public class Category { +public class Category implements BaseModel { private String name; private ArrayList specialProperties = new ArrayList<>(); private ArrayList products = new ArrayList<>(); diff --git a/src/main/java/model/Chat.java b/src/main/java/model/Chat.java new file mode 100644 index 0000000..304e7dd --- /dev/null +++ b/src/main/java/model/Chat.java @@ -0,0 +1,44 @@ +package model; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class Chat implements BaseModel { + private final String id; + boolean isPublic = false; + private final ArrayList usernames = new ArrayList<>(); // saves usernames + private final ArrayList messages = new ArrayList<>(); + + public Chat() { + this.id = UUID.randomUUID().toString(); + } + + public void setPublic(boolean isPublic) { + this.isPublic = isPublic; + } + + public void addUser(String username) { + usernames.add(username); + } + + public boolean hasUser(String userId) { + return isPublic || usernames.contains(userId); + } + + public void addMessage(ChatMessage message) { + messages.add(message); + } + + public List getMessages() { + return messages; + } + + public String getId() { + return id; + } + + public ArrayList getUsers() { + return usernames; + } +} diff --git a/src/main/java/model/ChatMessage.java b/src/main/java/model/ChatMessage.java new file mode 100644 index 0000000..566eb4f --- /dev/null +++ b/src/main/java/model/ChatMessage.java @@ -0,0 +1,28 @@ +package model; + +import java.time.LocalDateTime; +import java.util.UUID; + +public class ChatMessage { + private final String senderId; + private final LocalDateTime time; + private final String text; + + public ChatMessage(String senderId, String text) { + this.senderId = senderId; + this.text = text; + this.time = LocalDateTime.now(); + } + + public String getSenderId() { + return senderId; + } + + public LocalDateTime getTime() { + return time; + } + + public String getText() { + return text; + } +} diff --git a/src/main/java/model/Comment.java b/src/main/java/model/Comment.java index cb615db..4bf7508 100644 --- a/src/main/java/model/Comment.java +++ b/src/main/java/model/Comment.java @@ -6,13 +6,15 @@ import java.util.ArrayList; import java.util.UUID; -public class Comment { +public class Comment implements BaseModel { private String user; private String product; private String text; private String title; private LocalDate time; - private enum CommentStatus {WaitingForConfirmation,Confirmed, RejectedByManager} + + private enum CommentStatus {WaitingForConfirmation, Confirmed, RejectedByManager} + CommentStatus status = CommentStatus.WaitingForConfirmation; private boolean bought; private String id; @@ -79,7 +81,7 @@ public LocalDate getDate() { return time; } - public void addChild(Comment comment) { + public void addChild(Comment comment) throws Exception { childern.add(comment.getId()); Database.update(this, getId()); } diff --git a/src/main/java/model/Customer.java b/src/main/java/model/Customer.java index ce7f5bd..ac05bb2 100644 --- a/src/main/java/model/Customer.java +++ b/src/main/java/model/Customer.java @@ -14,6 +14,11 @@ public class Customer extends User { public Customer(String username, String name, String surname, String email, String phoneNumber, String password, long credit) { super(username, name, surname, email, phoneNumber, password, credit); + try { + this.bankAccountId = createBankAccount(); + System.out.println("successfully created bank account!"); + } catch (Exception ignored) { + } } @Override @@ -117,13 +122,6 @@ public int getProductInCart(String productId) { return 0; } - public void payCredit(long cost) throws Exception { - if (this.credit >= cost) - this.setCredit(this.getCredit() - cost); - else - throw new Exception("Not enough credit"); - } - public ArrayList getPurchaseHistory() { ArrayList purchaseLogs = new ArrayList<>(); for (String log : this.purchaseHistory) { diff --git a/src/main/java/model/Discount.java b/src/main/java/model/Discount.java index 2b9aa99..271ab5c 100644 --- a/src/main/java/model/Discount.java +++ b/src/main/java/model/Discount.java @@ -8,7 +8,7 @@ import java.util.Set; import java.util.UUID; -public class Discount { +public class Discount implements BaseModel { private String code; private LocalDateTime startTime; private LocalDateTime finishTime; @@ -135,7 +135,7 @@ public static String generateRandomCode () { return String.valueOf(randomCode); } - public static Discount getGiftDiscount (Customer customer, int percent) { + public static Discount getGiftDiscount(Customer customer, int percent) throws Exception { Discount discount = new Discount(); discount.addUser(customer); discount.setRepetitionNumber(1); diff --git a/src/main/java/model/Filter.java b/src/main/java/model/Filter.java index 5129977..8a0d01b 100644 --- a/src/main/java/model/Filter.java +++ b/src/main/java/model/Filter.java @@ -4,12 +4,17 @@ import java.util.ArrayList; import java.util.UUID; -public class Filter { +public class Filter implements BaseModel { private ArrayList properties = new ArrayList<>(); //some other properties are: //category, name, inStock(number property), brand, maxPrice, minPrice private String id; + @Override + public String getId() { + return id; + } + public Filter() { this.id = UUID.randomUUID().toString(); } diff --git a/src/main/java/model/Manager.java b/src/main/java/model/Manager.java index ee0f62f..2341c7c 100644 --- a/src/main/java/model/Manager.java +++ b/src/main/java/model/Manager.java @@ -1,5 +1,7 @@ package model; +import controller.Database; + public class Manager extends User { public Manager(String username, String name, String surname, String email, String phoneNumber, String password, long credit) { super(username, name, surname, email, phoneNumber, password, credit); diff --git a/src/main/java/model/NetworkArray.java b/src/main/java/model/NetworkArray.java new file mode 100644 index 0000000..ca9b9f2 --- /dev/null +++ b/src/main/java/model/NetworkArray.java @@ -0,0 +1,103 @@ +package model; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import controller.Database; + +import java.util.ArrayList; +import java.util.Iterator; + +public class NetworkArray extends ArrayList { + private ArrayList elementData = new ArrayList<>(); + private Class tClass; + + public NetworkArray(Class objectClass) { + tClass = objectClass; + } + + @Override + public int size() { + return elementData.size(); + } + + @Override + public boolean contains(Object o) { + BaseModel b; + try { + b = (BaseModel) o; + } catch (Exception ignore) { + return false; + } + return elementData.contains(b.getId()); + } + + @Override + public int indexOf(Object o) { + BaseModel b; + try { + b = (BaseModel) o; + } catch (Exception ignore) { + return -1; + } + return elementData.indexOf(b.getId()); + } + + @Override + public boolean add(T t) { + return elementData.add(t.getId()); + } + + @Override + public boolean remove(Object o) { + BaseModel b; + try { + b = (BaseModel) o; + } catch (Exception ignore) { + return false; + } + return elementData.remove(b.getId()); + } + + @Override + public Iterator iterator() { + try { + load(); + } catch (Exception e) { + e.printStackTrace(); + } + + return new Iterator() { + private int index = 0; + + @Override + public boolean hasNext() { + return index < elementData.size(); + } + + @Override + public T next() { + return get(index++); + } + + @Override + public void remove() { + + } + }; + } + + @Override + public T get(int index) { + try { + return (T) Database.getObjectFromNetwork(elementData.get(index), tClass); + } catch (Exception e) { + throw new NullPointerException("coudn't get the object"); + } + } + + public void load() throws Exception { + JsonObject jsonObject = Database.sendGETall(tClass); + elementData.clear(); + elementData.addAll(new Gson().fromJson(jsonObject.get("list"), elementData.getClass())); + } +} diff --git a/src/main/java/model/Off.java b/src/main/java/model/Off.java index f1f0aba..88a8f33 100644 --- a/src/main/java/model/Off.java +++ b/src/main/java/model/Off.java @@ -6,7 +6,7 @@ import java.util.List; import java.util.UUID; -public class Off { +public class Off implements BaseModel { private List products; private String sellerId; private OffStatus offStatus; diff --git a/src/main/java/model/PossibleManager.java b/src/main/java/model/PossibleManager.java new file mode 100644 index 0000000..158f79e --- /dev/null +++ b/src/main/java/model/PossibleManager.java @@ -0,0 +1,26 @@ +package model; + +import java.util.UUID; + +public class PossibleManager implements BaseModel { + private String id; + private String username; + + public PossibleManager() { + this.id = UUID.randomUUID().toString(); + } + + public PossibleManager(String username) { + this.username = username; + this.id = UUID.randomUUID().toString(); + } + + @Override + public String getId() { + return id; + } + + public String getUsername() { + return username; + } +} diff --git a/src/main/java/model/PossibleSupporter.java b/src/main/java/model/PossibleSupporter.java new file mode 100644 index 0000000..6d8aee2 --- /dev/null +++ b/src/main/java/model/PossibleSupporter.java @@ -0,0 +1,26 @@ +package model; + +import java.util.UUID; + +public class PossibleSupporter implements BaseModel { + private String id; + private String username; + + public PossibleSupporter() { + this.id = UUID.randomUUID().toString(); + } + + public PossibleSupporter(String username) { + this.username = username; + this.id = UUID.randomUUID().toString(); + } + + @Override + public String getId() { + return id; + } + + public String getUsername() { + return username; + } +} diff --git a/src/main/java/model/Product.java b/src/main/java/model/Product.java index 87ed2c4..40d299f 100644 --- a/src/main/java/model/Product.java +++ b/src/main/java/model/Product.java @@ -14,7 +14,7 @@ import java.util.Objects; import java.util.UUID; -public class Product { +public class Product implements BaseModel { private enum productStatus {WaitingForProduction, WaitingForEdition, Confirmed} private productStatus status = productStatus.WaitingForProduction; @@ -37,6 +37,16 @@ private enum productStatus {WaitingForProduction, WaitingForEdition, Confirmed} private String productImageAddress; private String videoAddress = null; + private String fileAddress; + + public String getFileAddress() { + return fileAddress; + } + + public void setFileAddress(String fileAdress) { + this.fileAddress = fileAdress; + } + public Product(String name, String brand, String price, String description, String seller, String category) { allScores = new ArrayList<>(); allComments = new ArrayList<>(); @@ -192,7 +202,7 @@ public ObservableList getAllSpecialProperties() { return result; } - public void setCategory(Category category) { + public void setCategory(Category category) throws Exception { this.category = category.getId(); allSpecialProperties = new ArrayList<>(); for (Property property : category.getSpecialProperties()) { @@ -328,7 +338,7 @@ public boolean hasOff() { return false; } - public SellLog createSellLog() { + public SellLog createSellLog() throws Exception { SellLog log = new SellLog(); log.setSoldProduct(this); log.setDate(LocalDateTime.now()); @@ -346,4 +356,11 @@ public void setId(String id) { public String toString() { return name + "\t" + brand; } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Product)) + return false; + return this.id.equals(((Product) obj).getId()); + } } \ No newline at end of file diff --git a/src/main/java/model/Property.java b/src/main/java/model/Property.java index 12b5079..065d419 100644 --- a/src/main/java/model/Property.java +++ b/src/main/java/model/Property.java @@ -2,7 +2,7 @@ import java.util.UUID; -public class Property { +public class Property implements BaseModel { private String name; private boolean isNumber; private long valueLong = 0; diff --git a/src/main/java/model/PurchaseLog.java b/src/main/java/model/PurchaseLog.java index 5c74bde..01af4b1 100644 --- a/src/main/java/model/PurchaseLog.java +++ b/src/main/java/model/PurchaseLog.java @@ -3,16 +3,17 @@ import controller.Database; import java.time.LocalDateTime; -import java.util.ArrayList; import java.util.HashMap; import java.util.UUID; -public class PurchaseLog { +public class PurchaseLog implements BaseModel { private LocalDateTime date; private long amountPaid; private String discount; private HashMap products;// + private enum deliveryStatus {InStock, Sent, Delivered} + deliveryStatus status = deliveryStatus.InStock; private String id; diff --git a/src/main/java/model/Request.java b/src/main/java/model/Request.java new file mode 100644 index 0000000..4527e6a --- /dev/null +++ b/src/main/java/model/Request.java @@ -0,0 +1,22 @@ +package model; + +import com.google.gson.JsonObject; + +public class Request implements BaseModel { + private String id; + private JsonObject jsonObject; + + public Request(JsonObject jsonObject) { + this.jsonObject = jsonObject; + this.id = jsonObject.get("id").getAsString(); + } + + @Override + public String getId() { + return id; + } + + public JsonObject getJsonObject() { + return jsonObject; + } +} diff --git a/src/main/java/model/Score.java b/src/main/java/model/Score.java index 9d0da14..5938c88 100644 --- a/src/main/java/model/Score.java +++ b/src/main/java/model/Score.java @@ -1,9 +1,10 @@ package model; import controller.Database; + import java.util.UUID; -public class Score { +public class Score implements BaseModel { private String user; private int score; private String product; diff --git a/src/main/java/model/SellLog.java b/src/main/java/model/SellLog.java index 18ad163..b0c5d19 100644 --- a/src/main/java/model/SellLog.java +++ b/src/main/java/model/SellLog.java @@ -3,20 +3,21 @@ import controller.Database; import java.time.LocalDateTime; -import java.util.HashMap; import java.util.UUID; -public class SellLog { +public class SellLog implements BaseModel { private LocalDateTime date; private long amountReceived; private long amountReduced; private String soldProduct; private String customer; + private enum shippingStatus {inStock, readyToPost, Posted} + shippingStatus status = shippingStatus.inStock; private String id; - public SellLog () { + public SellLog() { this.id = UUID.randomUUID().toString(); } public String getId() { diff --git a/src/main/java/model/Seller.java b/src/main/java/model/Seller.java index 8e976c0..970f74e 100644 --- a/src/main/java/model/Seller.java +++ b/src/main/java/model/Seller.java @@ -15,6 +15,10 @@ public Seller(String username, String name, String surname, String email, String super(username, name, surname, email, phoneNumber, password, credit); this.companyName = companyName; this.companyInfo = companyInfo; + try { + this.bankAccountId = createBankAccount(); + } catch (Exception ignored) { + } } public String getCompanyName() { diff --git a/src/main/java/model/Supporter.java b/src/main/java/model/Supporter.java new file mode 100644 index 0000000..978a145 --- /dev/null +++ b/src/main/java/model/Supporter.java @@ -0,0 +1,12 @@ +package model; + +public class Supporter extends User { + public Supporter(String username, String name, String surname, String email, String phoneNumber, String password, long credit) { + super(username, name, surname, email, phoneNumber, password, credit); + } + + @Override + public String getType() { + return "supporter"; + } +} diff --git a/src/main/java/model/User.java b/src/main/java/model/User.java index c114b98..03e4070 100644 --- a/src/main/java/model/User.java +++ b/src/main/java/model/User.java @@ -1,9 +1,18 @@ package model; +import com.google.gson.JsonObject; +import controller.Database; + import java.io.File; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; import java.util.UUID; -public abstract class User { +import static controller.Database.getJsonObjectFromReader; + +public abstract class User implements BaseModel { protected String username; protected String name; protected String surname; @@ -11,6 +20,7 @@ public abstract class User { protected String phoneNumber; protected String password; protected long credit; + protected String bankAccountId; protected String id; protected String birthDate = "2007-12-03"; protected String gender = "Prefer not to say"; @@ -61,10 +71,32 @@ public User(String username, String name, String surname, String email, String p this.id = UUID.randomUUID().toString(); } + protected String createBankAccount () throws Exception { + String url = Database.getServerUrl() + "createBankAccount" + "?firstName=" + + this.name.replaceAll("\\s", "_") + "&lastName=" + + this.surname.replaceAll("\\s", "_") + "&username=" + this.username + "&password=" + + this.password; + System.out.println(url); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", Database.getUserAgent()); + int responseCode = con.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + return convertedObject.get("accountId").getAsString(); + } + public String getId() { return id; } + public String getBankAccountId() { + return bankAccountId; + } + public String getEmail() { return email; } diff --git a/src/main/java/model/exception/DefaultUser.java b/src/main/java/model/exception/DefaultUser.java index 3eb4d0d..39e3c4f 100644 --- a/src/main/java/model/exception/DefaultUser.java +++ b/src/main/java/model/exception/DefaultUser.java @@ -6,7 +6,7 @@ public class DefaultUser extends Customer { public DefaultUser() { - super("","Anonymous User","", + super("","AnonymousUser","", "username@example.com","+98xxxxxxxxxx","",0); setUsername(getId()); } diff --git a/src/main/resources/fxml/AddProductPage.fxml b/src/main/resources/fxml/AddProductPage.fxml index a874df5..fcfd7b4 100644 --- a/src/main/resources/fxml/AddProductPage.fxml +++ b/src/main/resources/fxml/AddProductPage.fxml @@ -1,22 +1,13 @@ - - - + + + + - - - - - - - - - - @@ -63,6 +54,12 @@ + + + + diff --git a/src/main/resources/fxml/AddSupporterMenu.fxml b/src/main/resources/fxml/AddSupporterMenu.fxml new file mode 100644 index 0000000..d8c4838 --- /dev/null +++ b/src/main/resources/fxml/AddSupporterMenu.fxml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/fxml/MainMenu.fxml b/src/main/resources/fxml/MainMenu.fxml index 6ca5874..ddf4773 100644 --- a/src/main/resources/fxml/MainMenu.fxml +++ b/src/main/resources/fxml/MainMenu.fxml @@ -1,15 +1,12 @@ - - - @@ -23,7 +20,7 @@ - + diff --git a/src/main/resources/fxml/ManagerPage.fxml b/src/main/resources/fxml/ManagerPage.fxml index 7536025..f6a28d7 100644 --- a/src/main/resources/fxml/ManagerPage.fxml +++ b/src/main/resources/fxml/ManagerPage.fxml @@ -20,8 +20,10 @@ + + diff --git a/src/main/resources/fxml/PaymentPage.fxml b/src/main/resources/fxml/PaymentPage.fxml index ac051b3..e987fa2 100644 --- a/src/main/resources/fxml/PaymentPage.fxml +++ b/src/main/resources/fxml/PaymentPage.fxml @@ -27,6 +27,11 @@