diff options
25 files changed, 250 insertions, 123 deletions
diff --git a/docs/DesignDoc.md b/docs/DesignDoc.md index 0a92bac..7f1c457 100644 --- a/docs/DesignDoc.md +++ b/docs/DesignDoc.md @@ -167,9 +167,13 @@ In our model tier we have a Need class, a User class, and a UserAuth class. The > _**[Sprint 1]** Name and describe the initial OO Principles that your team has considered in support of your design (and implementation) for this first Sprint._ - Law of Demeter: Classes only talk to nearby classes. + - This principle is used to ensure that unintended behavior is minimal, by making each class only talk to others that make sense in the scope of the application. For example, the `dashboard` component interacts with the `need-list` and `funding-basket` components because they are needed to display needs on the dashboard, but it does not interact with the `login` or `signup` components, as they are not needed in order to ensure the functionality of the dashboard. These are located in the ViewModel and Model Tiers. - Low Coupling: Limit the number of classes connected to each individual class. + - We use Low Coupling principles to ensure that only classes related in function are actually interacting with each other. In our Angular setup, classes interact with their respective services instead of sharing the data with other classes. `NeedService` connects to `need-page`, `need-list`, `funding-basket`, and `cupboard`, but the components themselves do not interact with each other. This is more efficient and prevents one component from stalling if another errors. Because the service exclusively handles CRUD operations, it will not cause the connected components to stall if it encounters an error. These examples are located in the ViewModel Tier. - Pure Fabrication: Using helper functions to split up larger classes into more managable chunks. + - For example, this principle is showcased in our `AuthService`. Instead of having the `UserService` handle user management and user authorization at the same time, we have split the authorization part into a new AuthService class to handle login, while the UserService handles just the CRUD operations pertaining to the user. These classes are located in the ViewModel Tier. - Single Responsibility: Each function should only have one function to prevent unintended errors. + - This principle is used in our `CupboardController`, as it's only functionality is to connect the front-end and back-end through our REST API. This means that cupboard-related operations are not backlogged by any other classes, which is efficient and prevents unintended behavior in the application. This can be seen in the Model Tier. > _**[Sprint 2, 3 & 4]** Will eventually address upto **4 key OO Principles** in your final design. Follow guidance in augmenting those completed in previous Sprints as indicated to you by instructor. Be sure to include any diagrams (or clearly refer to ones elsewhere in your Tier sections above) to support your claims._ diff --git a/ufund-api/data/cupboard.json b/ufund-api/data/cupboard.json index 0e3917f..493d7fa 100644 --- a/ufund-api/data/cupboard.json +++ b/ufund-api/data/cupboard.json @@ -1 +1 @@ -[{"name":"Pollution Filters","location":"New York Harbor","id":5,"maxGoal":1000.0,"type":"PHYSICAL","urgent":true,"filterAttributes":[],"current":0.0,"description":"One thousand heavy duty pollution filters need to be installed as soon as possible throughout the new york harbor."},{"name":"Diving Equipment","location":"Gulf of Mexico","id":6,"maxGoal":120000.0,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"Our research team in mexico needs new deep sea rated equipment to continue their research on the ecosystem! Until the equipment funding is fully reached and gear installed, no more progress can be made."},{"name":"Dog Fish research","location":"RIT","id":8,"maxGoal":1000000.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"Dog Fish are a very interesting species that many research facilities are not researching. The funding will go towards starting research papers on the species."},{"name":"Fish Food Promotion","location":"","id":10,"maxGoal":1000.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"The money will be spent on a small advertising campaign at a local pet store, where free fish food will be given out to people willing to listen to our cause."},{"name":"Harpoons","location":"Atlantic City","id":11,"maxGoal":25.0,"type":"PHYSICAL","urgent":false,"filterAttributes":[],"current":0.0,"description":"Harpoons are needed for an upcoming whaling museum exhibit. We aren't picky, and need any harpoons that would be interesting for display. We are accepting any harpoons at least 30 years old, but the older the better."},{"name":"Sea Urchin Hats","location":"Seaworld","id":12,"maxGoal":90.0,"type":"PHYSICAL","urgent":true,"filterAttributes":[],"current":0.0,"description":"Seaworld's sea urchins will be wearing your hats as a part of a promo! Hats donated will be used as a part of an awareness exhibit at Seaworld."},{"name":"Awareness Exhibit","location":"Seneca Park Zoo","id":13,"maxGoal":1.0E7,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"Getting the Jelly Solutions message out is our top priority. We would like to open a large exhibit featuring all the endangered species due to climate change, overfishing, and pollution. Sadly, this wouldn't be cheap as we want to really get the message across to visitors through different animals, scenes, info boards, and videos."},{"name":"New Whale","location":"Seneca Park Zoo","id":14,"maxGoal":1.0,"type":"PHYSICAL","urgent":false,"filterAttributes":[],"current":0.0,"description":"Seneca park zoo needs a new whale for the upcoming promotional exhibit! The zoo will provide a commemorative plaque for the donor."},{"name":"New Gosnell Algae Filter","location":"Gosnell College","id":15,"maxGoal":40.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"The Gosnell College fish tank gets way to dirty way too quickly. $40 surely could replace the filter with a more effective one."},{"name":"Awareness Lunches","location":"Colleges and Highschools","id":16,"maxGoal":5000.0,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"College and Highschool students would be great recruits for our volunteer events. The lunches would promote our cause and demonstrate ways that they could easily contribute to the movement."},{"name":"Fish Column for RIT Tours","location":"Wallace Library","id":17,"maxGoal":2.0E7,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"RIT tours always run through Wallace Library into the SHED. What better way to encourage students to attend the college than a massive aquarium column? This would not only encourage students to join RIT, and could also raise awareness for our cause."},{"name":"Submarine Matinience","location":"New York Harbor","id":18,"maxGoal":1000000.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"Submarines are necessary tools that many other needs cannot function without. These urgent repairs need to happen as soon as possible."},{"name":"Volunteering for Volunteer Lunches ","location":"Lake Ontario","id":19,"maxGoal":5.0,"type":"PHYSICAL","urgent":false,"filterAttributes":[],"current":0.0,"description":"We need staff to help organize our awareness lunches! The lunches will recruit interested people into volunteering for upcoming events and cleanups."},{"name":"Volunteer Misc. Equipment","location":"Lake Ontario","id":20,"maxGoal":2500.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"$2500 is needed to cover the unforeseen costs of the upcoming beach cleanup. The money will be spent on nets and other tools for volunteers."},{"name":"Invasive eel removal","location":"Pacific Seafloor","id":21,"maxGoal":1.0E8,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"The population of invasive eels are destroying ecosystems. We need to remove these eels and restore balance to these ecosystems as soon as possible."},{"name":"Fishing Liscense Enforcement","location":"Rochester Bridges","id":22,"maxGoal":10000.0,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"Rochester citizens won't stop fishing off bridges no matter how many times we ask. The funding will go to increased enforcement of fishing licenses in delegated stocked areas."},{"name":"Waste Runoff Management","location":"RIT Watershed","id":23,"maxGoal":98000.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"Waste runoff into the protected watershed near RIT is a consistent issue. We need funding to research how to best solve this problem."},{"name":"Lobbying for anti-dynamite fishing legislation","location":"Washington DC","id":24,"maxGoal":50000.0,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"Dynamite fishing destroys ecosystems. Legislation needs to be passed as soon as possible! However, lobbyists aren't cheap. Any support to the fund would be greatly appreciated."},{"name":"Bioluminescence Tunnel","location":"Golisano College of Computing","id":26,"maxGoal":2.8E7,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"Golisano needs a biolumenescence tunnel! The addition would be costly, but would make the building much more interesting to be in. People sometimes complain about the way the building feels, and this would be a great way to fix that."}]
\ No newline at end of file +[{"name":"Pollution Filters","image":"https://www.water-pollutionsolutions.com/image-files/trash-boom-400x400.webp","location":"New York Harbor","id":5,"maxGoal":1000.0,"type":"PHYSICAL","urgent":true,"filterAttributes":[],"current":0.0,"description":"One thousand heavy duty pollution filters need to be installed as soon as possible throughout the new york harbor."},{"name":"Diving Equipment","image":"https://www.tripsavvy.com/thmb/1Kb4aOEh0hulYSUdvc2lfYp9xUU=/1500x0/filters:no_upscale():max_bytes(150000):strip_icc()/full-set-of-scuba-diving-equipment--scuba-gear-and-accessories--1223442535-7472dd1b3cc647b7a0240e4ff28577c1.jpg","location":"Gulf of Mexico","id":6,"maxGoal":120000.0,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"Our research team in mexico needs new deep sea rated equipment to continue their research on the ecosystem! Until the equipment funding is fully reached and gear installed, no more progress can be made."},{"name":"Dog Fish research","image":"https://i.ytimg.com/vi/5y9wG0o2oys/maxresdefault.jpg","location":"RIT","id":8,"maxGoal":1000000.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"Dog Fish are a very interesting species that many research facilities are not researching. The funding will go towards starting research papers on the species."},{"name":"Fish Food Promotion","image":"https://www.newsservice.org/getimage.php?p=c2dpZD0zNDA1OSZzaWQ9MQ==","location":"PETCO","id":10,"maxGoal":1000.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"The money will be spent on a small advertising campaign at a local pet store, where free fish food will be given out to people willing to listen to our cause."},{"name":"Harpoons","image":"https://cdn.images.express.co.uk/img/dynamic/151/590x/Sperm-whales-sperm-1411080.jpg?r=1616059298592","location":"Atlantic City","id":11,"maxGoal":25.0,"type":"PHYSICAL","urgent":false,"filterAttributes":[],"current":0.0,"description":"Harpoons are needed for an upcoming whaling museum exhibit. We aren't picky, and need any harpoons that would be interesting for display. We are accepting any harpoons at least 30 years old, but the older the better."},{"name":"Sea Urchin Hats","image":"https://i.etsystatic.com/iap/3c0935/4347866713/iap_640x640.4347866713_7nns9y41.jpg?version=0","location":"Seaworld","id":12,"maxGoal":90.0,"type":"PHYSICAL","urgent":true,"filterAttributes":[],"current":0.0,"description":"Seaworld's sea urchins will be wearing your hats as a part of a promo! Hats donated will be used as a part of an awareness exhibit at Seaworld."},{"name":"Awareness Exhibit","image":null,"location":"Seneca Park Zoo","id":13,"maxGoal":1.0E7,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"Getting the Jelly Solutions message out is our top priority. We would like to open a large exhibit featuring all the endangered species due to climate change, overfishing, and pollution. Sadly, this wouldn't be cheap as we want to really get the message across to visitors through different animals, scenes, info boards, and videos."},{"name":"New Whale","image":"https://s.abcnews.com/images/GMA/150721_gma_aquarium_4x3_992.jpg","location":"Seneca Park Zoo","id":14,"maxGoal":1.0,"type":"PHYSICAL","urgent":false,"filterAttributes":[],"current":0.0,"description":"Seneca park zoo needs a new whale for the upcoming promotional exhibit! The zoo will provide a commemorative plaque for the donor."},{"name":"New Gosnell Algae Filter","image":"https://i.redd.it/my-tank-is-gross-and-im-confused-v0-4mje2n8ggawc1.jpg?width=4032&format=pjpg&auto=webp&s=68ef0f53cc4cf1287b3804241708b67de00f4744","location":"Gosnell College","id":15,"maxGoal":40.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"The Gosnell College fish tank gets way to dirty way too quickly. $40 surely could replace the filter with a more effective one."},{"name":"Awareness Lunches","image":"https://northernontario.travel/sites/default/files/Shore-lunch-CTA.jpg","location":"Colleges and Highschools","id":16,"maxGoal":5000.0,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"College and Highschool students would be great recruits for our volunteer events. The lunches would promote our cause and demonstrate ways that they could easily contribute to the movement."},{"name":"Fish Column for RIT Tours","image":"https://compote.slate.com/images/0217aba0-941b-4744-b33a-5d32a202db2f.jpeg?crop=1560%2C1040%2Cx0%2Cy0","location":"Wallace Library","id":17,"maxGoal":2.0E7,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"RIT tours always run through Wallace Library into the SHED. What better way to encourage students to attend the college than a massive aquarium column? This would not only encourage students to join RIT, and could also raise awareness for our cause."},{"name":"Submarine Matinience","image":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSerbMu_phBKjF_tsA4JYthKQDJgcU9OAGzeg&s","location":"New York Harbor","id":18,"maxGoal":1000000.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"Submarines are necessary tools that many other needs cannot function without. These urgent repairs need to happen as soon as possible."},{"name":"Volunteering for Volunteer Lunches ","image":"https://images.squarespace-cdn.com/content/v1/62827154bc55076eba9aef96/1654613291356-UEY844JXKFN9UXDVRTKQ/image-asset.jpeg","location":"Lake Ontario","id":19,"maxGoal":5.0,"type":"PHYSICAL","urgent":false,"filterAttributes":[],"current":0.0,"description":"We need staff to help organize our awareness lunches! The lunches will recruit interested people into volunteering for upcoming events and cleanups."},{"name":"Volunteer Misc. Equipment","image":"https://montereybay.noaa.gov/media/getinvolved/images/bn2.jpg","location":"Lake Ontario","id":20,"maxGoal":2500.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"$2500 is needed to cover the unforeseen costs of the upcoming beach cleanup. The money will be spent on nets and other tools for volunteers."},{"name":"Invasive eel removal","image":"https://www.louisianasportsman.com/wp-content/uploads/2019/06/IMG_2252.jpg","location":"Pacific Seafloor","id":21,"maxGoal":1.0E8,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"The population of invasive eels are destroying ecosystems. We need to remove these eels and restore balance to these ecosystems as soon as possible."},{"name":"Fishing Liscense Enforcement","image":"https://i.ytimg.com/vi/vNHAutSs4o4/sddefault.jpg","location":"Rochester Bridges","id":22,"maxGoal":10000.0,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"Rochester citizens won't stop fishing off bridges no matter how many times we ask. The funding will go to increased enforcement of fishing licenses in delegated stocked areas."},{"name":"Waste Runoff Management","image":"https://cdn.rit.edu/images/news/2024-09/WEB-StormDrain.jpg","location":"RIT Watershed","id":23,"maxGoal":98000.0,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"Waste runoff into the protected watershed near RIT is a consistent issue. We need funding to research how to best solve this problem."},{"name":"Lobbying for anti-dynamite fishing legislation","image":"https://s.abcnews.com/images/US/dynamite-gty-jpo-180907_hpMain_16x9_992.jpg","location":"Washington DC","id":24,"maxGoal":50000.0,"type":"MONETARY","urgent":false,"filterAttributes":[],"current":0.0,"description":"Dynamite fishing destroys ecosystems. Legislation needs to be passed as soon as possible! However, lobbyists aren't cheap. Any support to the fund would be greatly appreciated."},{"name":"Bioluminescence Tunnel","image":"https://img.atlasobscura.com/sKxcO-wY9ue650ypcUmSqJAWNMxQZGtaYpZZ1Z7jQ-E/rs:fill:780:520:1/g:ce/q:81/sm:1/scp:1/ar:1/aHR0cHM6Ly9hdGxh/cy1kZXYuczMuYW1h/em9uYXdzLmNvbS91/cGxvYWRzL2Fzc2V0/cy9kMzg0NzYyNmZl/OWJhNTEwNzJfZ2xv/d3dvcm1jYXZlLmpw/Zw.jpg","location":"Golisano College of Computing","id":26,"maxGoal":2.8E7,"type":"MONETARY","urgent":true,"filterAttributes":[],"current":0.0,"description":"Golisano needs a biolumenescence tunnel! The addition would be costly, but would make the building much more interesting to be in. People sometimes complain about the way the building feels, and this would be a great way to fix that."}]
\ No newline at end of file diff --git a/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/CupboardController.java b/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/CupboardController.java index 12fb0a9..075878a 100644 --- a/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/CupboardController.java +++ b/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/CupboardController.java @@ -1,6 +1,7 @@ package com.ufund.api.ufundapi.controller; import java.io.IOException; +import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; @@ -189,12 +190,22 @@ public class CupboardController { * @return OK if successful, other statuses if failure */ @PutMapping("/checkout") - public ResponseEntity<Object> checkoutNeeds(@RequestBody Map<String, Integer> data, @RequestHeader("jelly-api-key") String key) { - int needID = data.get("needID"); - int checkoutAmount = data.get("amount"); - LOG.log(Level.INFO, "PUT /need/checkout body={0}", data); + public ResponseEntity<Object> checkoutNeeds(@RequestBody List<Map<String, Integer>> data, @RequestHeader("jelly-api-key") String key) { + LOG.log(Level.INFO, "PUT /cupboard/checkout body={0}", data); try { - cupboardService.checkoutNeed(needID, checkoutAmount, key); + authService.keyIsValid(key); + + for (Map<String, Integer> map : data) { + int needID = map.get("needID"); + if (cupboardService.getNeed(needID) == null) { + return new ResponseEntity<>("One or more need is invalid, please refresh.", HttpStatus.BAD_REQUEST); + } + } + for (Map<String, Integer> map : data) { + int needID = map.get("needID"); + int checkoutAmount = map.get("quantity"); + cupboardService.checkoutNeed(needID, checkoutAmount, key); + } return new ResponseEntity<>(HttpStatus.OK); } catch (IllegalArgumentException ex) { LOG.log(Level.WARNING, ex.getLocalizedMessage()); diff --git a/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/UserController.java b/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/UserController.java index a34e891..6953276 100644 --- a/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/UserController.java +++ b/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/UserController.java @@ -95,6 +95,32 @@ public class UserController { } /** + * Responds to the GET request with the total number of users + * + * @param key The authentication key of the user + * @return ResponseEntity with amount and HTTP status of OK<br> + * ResponseEntity with HTTP status of UNAUTHORIZED if user is not aa manager<br> + * ResponseEntity with HTTP status of INTERNAL_SERVER_ERROR otherwise + */ + @GetMapping("/count") + public ResponseEntity<Object> getUserCount(@RequestHeader("jelly-api-key") String key) { + LOG.log(Level.INFO, "GET /userAmount"); + + try { + authService.keyHasAccessToCupboard(key); + String count = String.valueOf(userService.getUserCount()); + return new ResponseEntity<>(count, HttpStatus.OK); + } catch (IllegalAccessException ex) { + LOG.log(Level.WARNING, ex.getLocalizedMessage()); + return new ResponseEntity<>(ex.getMessage(), HttpStatus.UNAUTHORIZED); + } catch (IOException ex) { + LOG.log(Level.SEVERE, ex.getLocalizedMessage()); + return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + + } + + /** * Updates a User with the provided one * * @param user The user to update diff --git a/ufund-api/src/main/java/com/ufund/api/ufundapi/persistence/UserDAO.java b/ufund-api/src/main/java/com/ufund/api/ufundapi/persistence/UserDAO.java index 29d46cf..27ba0b9 100644 --- a/ufund-api/src/main/java/com/ufund/api/ufundapi/persistence/UserDAO.java +++ b/ufund-api/src/main/java/com/ufund/api/ufundapi/persistence/UserDAO.java @@ -34,6 +34,16 @@ public interface UserDAO { User getUser(String username) throws IOException; /** + * Retrieves the total count of users + * + * @return a {@link int amount} number of users + * <br> + * + * @throws IOException if an issue with underlying storage + */ + int getUserCount() throws IOException; + + /** * Creates and saves a {@linkplain User user} * * @param user {@linkplain User user} object to be created and saved diff --git a/ufund-api/src/main/java/com/ufund/api/ufundapi/persistence/UserFileDAO.java b/ufund-api/src/main/java/com/ufund/api/ufundapi/persistence/UserFileDAO.java index ec94da8..7f1fadd 100644 --- a/ufund-api/src/main/java/com/ufund/api/ufundapi/persistence/UserFileDAO.java +++ b/ufund-api/src/main/java/com/ufund/api/ufundapi/persistence/UserFileDAO.java @@ -58,6 +58,13 @@ public class UserFileDAO implements UserDAO { } @Override + public int getUserCount() { + synchronized (users) { + return users.size(); + } + } + + @Override public User getUser(String username) { synchronized (users) { return users.getOrDefault(username, null); diff --git a/ufund-api/src/main/java/com/ufund/api/ufundapi/service/UserService.java b/ufund-api/src/main/java/com/ufund/api/ufundapi/service/UserService.java index 6e27f50..8b34e68 100644 --- a/ufund-api/src/main/java/com/ufund/api/ufundapi/service/UserService.java +++ b/ufund-api/src/main/java/com/ufund/api/ufundapi/service/UserService.java @@ -56,6 +56,16 @@ public class UserService { } /** + * Returns the total number of users + * + * @return The number of users + * @throws IOException If there was any problem saving the file + */ + public int getUserCount() throws IOException { + return userDAO.getUserCount(); + } + + /** * Updates a user * * @param user The ID of the user to update diff --git a/ufund-api/src/test/java/com/ufund/api/ufundapi/controller/CupboardControllerTest.java b/ufund-api/src/test/java/com/ufund/api/ufundapi/controller/CupboardControllerTest.java index 8572ec6..7ea4455 100644 --- a/ufund-api/src/test/java/com/ufund/api/ufundapi/controller/CupboardControllerTest.java +++ b/ufund-api/src/test/java/com/ufund/api/ufundapi/controller/CupboardControllerTest.java @@ -1,6 +1,7 @@ package com.ufund.api.ufundapi.controller; import java.io.IOException; +import java.util.List; import java.util.Map; import static java.util.Map.entry; @@ -418,12 +419,14 @@ public class CupboardControllerTest { @Test public void checkoutNeeds() throws IOException, IllegalAccessException { + when(mockCupboardService.getNeed(0)).thenReturn(new Need("name", "image", "location", 0, 10, GoalType.MONETARY, true, "a")); doNothing().when(mockCupboardService).checkoutNeed(0, 20, key); - - Map<String, Integer> needMap = Map.ofEntries( - entry("needID", 0), - entry("amount", 20) + var needMap = List.of( + Map.ofEntries( + entry("needID", 0), + entry("quantity", 20) + ) ); var res = cupboardController.checkoutNeeds(needMap, key); @@ -435,9 +438,15 @@ public class CupboardControllerTest { public void checkoutNeedsBadRequest() throws IOException, IllegalAccessException { doThrow(new IllegalArgumentException()).when(mockCupboardService).checkoutNeed(0, 20, key); - Map<String, Integer> needMap = Map.ofEntries( - entry("needID", 0), - entry("amount", 20) + var needMap = List.of( + Map.ofEntries( + entry("needID", 0), + entry("quantity", 20) + ), + Map.ofEntries( + entry("needID", 2), + entry("quantity", 30) + ) ); var res = cupboardController.checkoutNeeds(needMap, key); @@ -447,11 +456,17 @@ public class CupboardControllerTest { @Test public void checkoutNeedsUnauthorized() throws IOException, IllegalAccessException { - doThrow(new IllegalAccessException()).when(mockCupboardService).checkoutNeed(0, 20, key); - - Map<String, Integer> needMap = Map.ofEntries( - entry("needID", 0), - entry("amount", 20) + doThrow(new IllegalAccessException()).when(mockAuthService).keyIsValid(key); + + var needMap = List.of( + Map.ofEntries( + entry("needID", 0), + entry("quantity", 20) + ), + Map.ofEntries( + entry("needID", 2), + entry("quantity", 30) + ) ); var res = cupboardController.checkoutNeeds(needMap, key); @@ -461,11 +476,14 @@ public class CupboardControllerTest { @Test public void checkoutNeedsInternalError() throws IOException, IllegalAccessException { + when(mockCupboardService.getNeed(0)).thenReturn(new Need("name", "image", "location", 0, 10, GoalType.MONETARY, true, "a")); doThrow(new IOException()).when(mockCupboardService).checkoutNeed(0, 20, key); - Map<String, Integer> needMap = Map.ofEntries( - entry("needID", 0), - entry("amount", 20) + var needMap = List.of( + Map.ofEntries( + entry("needID", 0), + entry("quantity", 20) + ) ); var res = cupboardController.checkoutNeeds(needMap, key); diff --git a/ufund-ui/public/placeholder.png b/ufund-ui/public/placeholder.png Binary files differnew file mode 100644 index 0000000..5b86fb7 --- /dev/null +++ b/ufund-ui/public/placeholder.png diff --git a/ufund-ui/src/app/components/dashboard/dashboard.component.html b/ufund-ui/src/app/components/dashboard/dashboard.component.html index 2d7b4c3..2af467c 100644 --- a/ufund-ui/src/app/components/dashboard/dashboard.component.html +++ b/ufund-ui/src/app/components/dashboard/dashboard.component.html @@ -4,7 +4,11 @@ <!--<app-mini-need-list [needList]="almostThere" jtitle="Almost there" url="/cupboard"/>--> <!--<app-mini-need-list [needList]="inBasket" jtitle="In your basket" url="/basket"/>--> <span>_ Registered users</span> -<span>_ Needs with overflow</span> -<span>_ Needs in peoples baskets</span> +<span *ngIf="count"> {{count | async}} </span> +<span>_ Fulfilled needs</span> +<app-mini-need-list [needList]="fulfilledNeeds.getValue()" jtitle="Fulfilled needs"> </app-mini-need-list> +<span>_ Most fulfilled needs</span> +<app-mini-need-list [needList]="mostFulfilledNeeds.getValue()" jtitle="Most fulfilled"> </app-mini-need-list> <span>_ Total monetary contributions</span> +<span *ngIf="totalDonations">${{totalDonations | async}} </span> <span>_ </span> diff --git a/ufund-ui/src/app/components/dashboard/dashboard.component.ts b/ufund-ui/src/app/components/dashboard/dashboard.component.ts index c94b5c6..9bf7627 100644 --- a/ufund-ui/src/app/components/dashboard/dashboard.component.ts +++ b/ufund-ui/src/app/components/dashboard/dashboard.component.ts @@ -1,10 +1,10 @@ import {Component, OnInit} from '@angular/core'; import {AuthService} from '../../services/auth.service'; import {Router} from '@angular/router'; -import {Need} from '../../models/Need'; import {CupboardService} from '../../services/cupboard.service'; -import {firstValueFrom} from 'rxjs'; import {UsersService} from '../../services/users.service'; +import {BehaviorSubject} from 'rxjs'; +import {GoalType, Need} from '../../models/Need'; @Component({ selector: 'app-dashboard', @@ -14,9 +14,11 @@ import {UsersService} from '../../services/users.service'; }) export class DashboardComponent implements OnInit{ - topNeeds?: Need[] - almostThere?: Need[] - inBasket?: Need[] + protected count = new BehaviorSubject<number | undefined>(undefined) + protected totalDonations = new BehaviorSubject<number | undefined>(undefined) + protected totalNeeds = new BehaviorSubject<number | undefined>(undefined) + protected fulfilledNeeds = new BehaviorSubject<Need[] | undefined>(undefined) + protected mostFulfilledNeeds = new BehaviorSubject<Need[] | undefined>(undefined) constructor( protected authService: AuthService, @@ -32,14 +34,25 @@ export class DashboardComponent implements OnInit{ return } - firstValueFrom(this.cupboardService.getNeeds()).then(r => { - this.topNeeds = r.sort((a, b) => b.current - a.current) - this.almostThere = r.sort((a, b) => a.current/a.maxGoal - b.current/b.maxGoal) - }) + this.userService.getCount().subscribe(count => this.count.next(count)) + this.cupboardService.getNeeds().subscribe(needs => { + let totalValue = 0 + for (let need of needs) { + if (need.type === GoalType.MONETARY) { + totalValue += need.current + this.totalDonations.next(totalValue) + } + + } + this.fulfilledNeeds.next(needs.filter(a => ((a.current / a.maxGoal)) >= 1)) + needs.sort((a, b) => b.current/b.maxGoal - a.current/a.maxGoal) - this.userService.getBasket().subscribe(r => { - this.inBasket = r; + needs = needs.filter(a => a.current != 0) + this.totalNeeds.next(needs.length) + this.mostFulfilledNeeds.next(needs.slice(0, 5)) }) + + } } diff --git a/ufund-ui/src/app/components/funding-basket/funding-basket.component.html b/ufund-ui/src/app/components/funding-basket/funding-basket.component.html index fcd5437..3f840e1 100644 --- a/ufund-ui/src/app/components/funding-basket/funding-basket.component.html +++ b/ufund-ui/src/app/components/funding-basket/funding-basket.component.html @@ -3,7 +3,7 @@ <h1>Funding Basket</h1> <ng-template [ngIf]="(usersService.getBasket() | async)?.length"> <ng-template let-need #NLActions> - <input type="number" placeholder="Quantity" min="1" [id]="need?.id" class="contribution"> + <input type="number" placeholder="Quantity" min="1" [id]="need?.id" class="contribution" (input)="resetColor($event)"> <button class="removeNeed" (click)="this.usersService.removeNeed(need.id)"> <span class="icon">delete</span>Remove from Basket </button> diff --git a/ufund-ui/src/app/components/funding-basket/funding-basket.component.ts b/ufund-ui/src/app/components/funding-basket/funding-basket.component.ts index 767327e..c807271 100644 --- a/ufund-ui/src/app/components/funding-basket/funding-basket.component.ts +++ b/ufund-ui/src/app/components/funding-basket/funding-basket.component.ts @@ -24,68 +24,44 @@ export class FundingBasketComponent implements OnInit { ) {} @ViewChild("contribution") contribution?: Input; - @Input() isValid: boolean = true; ngOnInit(): void { this.usersService.refreshBasket(); - // this.usersService.removeNeed(); <- call this to remove } async checkout() { - this.isValid = true; - for (let c of document.querySelectorAll('.contribution')!) { - let contribution = c as HTMLInputElement; - contribution.setAttribute("style", ""); - if (contribution.value == '' || contribution.valueAsNumber <= 0) { - this.isValid = false; + let order: { needID: number, quantity: number }[] = [] + let isNotValid = false + for (let contribution of document.querySelectorAll<HTMLInputElement>('.contribution')!) { + if (contribution.value == '' || contribution.valueAsNumber <= 0) { + isNotValid = true contribution.setAttribute("style", "border-color: #ff0000"); - this.toastService.sendToast(ToastType.ERROR, "Invalid input in funding basket!") - - setTimeout(() => { - contribution.setAttribute("style", "border-color: #ffffff"); - }, 3000); } + order.push({needID: +contribution.id, quantity: contribution.valueAsNumber}); } - // if (this.usersService.getBasket().value != await firstValueFrom(this.usersService.getUser(1)) - // for (let c of this.usersService.getBasket().value) { - // if (c == null) { - // this.isValid = false; - // this.statusText.next("One or more needs have been deleted") - // } else { - // this.statusText.next("test") - // } - // } - if (this.isValid) { - for (let c of document.querySelectorAll('.contribution')!) { - let contribution = c as HTMLInputElement; - let need = await firstValueFrom(this.cupboardService.getNeed(+contribution.id)); - need.current += +contribution.value; - this.usersService.removeNeed(+need.id); - this.cupboardService.checkoutNeed(need.id, +contribution.value) - .pipe(catchError((ex, _) => { - if (ex.status == 500) { - this.toastService.sendToast(ToastType.ERROR, 'Fields cannot be blank'); - } else if (ex.status == 400) { - this.toastService.sendToast(ToastType.ERROR, ex.error); - } else { - this.toastService.sendToast(ToastType.ERROR, 'Error on creating need'); - } - return new Observable<string>(); - })) - .subscribe((result) => { - if (result) { - //this.needList?.refresh() - } else { - console.log('need update failed'); - } - this.toastService.sendToast(ToastType.INFO, "Checkout successful"); - }); - } + + if (isNotValid) { + this.toastService.sendToast(ToastType.ERROR, "Invalid input in funding basket!") + return; } + + try { + await firstValueFrom(this.cupboardService.checkoutNeed(order)) + } catch (ex:any) { + this.toastService.sendToast(ToastType.ERROR, ex.error); + return + } + + order.forEach(contribution => this.usersService.removeNeed(contribution.needID)) + this.toastService.sendToast(ToastType.INFO, "Checkout successful"); } + resetColor(ev: any) { + // for (let contribution of document.querySelectorAll<HTMLInputElement>('.contribution')!) {} + (ev.target as HTMLInputElement).setAttribute("style", "border-color: unset") + } protected readonly of = of; protected readonly userType = userType; diff --git a/ufund-ui/src/app/components/mini-need-list/mini-need-list.component.css b/ufund-ui/src/app/components/mini-need-list/mini-need-list.component.css index ac456ab..090bea9 100644 --- a/ufund-ui/src/app/components/mini-need-list/mini-need-list.component.css +++ b/ufund-ui/src/app/components/mini-need-list/mini-need-list.component.css @@ -23,7 +23,7 @@ padding: 10px; gap: 10px; justify-content: start; - overflow: clip; + overflow: auto; } .needEntry { diff --git a/ufund-ui/src/app/components/mini-need-list/mini-need-list.component.html b/ufund-ui/src/app/components/mini-need-list/mini-need-list.component.html index a2de9e5..9febfa5 100644 --- a/ufund-ui/src/app/components/mini-need-list/mini-need-list.component.html +++ b/ufund-ui/src/app/components/mini-need-list/mini-need-list.component.html @@ -1,6 +1,6 @@ <div id="header"> <span>{{jtitle}}</span> - <a [routerLink]="url">Show All<span class="icon">arrow_forward_ios</span></a> + <a *ngIf="url" [routerLink]="url">Show All<span class="icon">arrow_forward_ios</span></a> </div> <div id="needList"> diff --git a/ufund-ui/src/app/components/need-list/need-list.component.html b/ufund-ui/src/app/components/need-list/need-list.component.html index ffed91d..406bfa0 100644 --- a/ufund-ui/src/app/components/need-list/need-list.component.html +++ b/ufund-ui/src/app/components/need-list/need-list.component.html @@ -16,7 +16,8 @@ <div class="prog"> <span id="hover-status-label-{{need.id}}"> </span> - <span>{{need.current}}/{{need.maxGoal}} ({{((need.current / need.maxGoal) * 100).toFixed(0)}}%)</span> + + <span>{{need.type.toString() == 'MONETARY' ? '$' : ''}}{{need.current}}/{{need.type.toString() == 'MONETARY' ? '$' : ''}}{{need.maxGoal}} ({{((need.current / need.maxGoal) * 100).toFixed(0)}}%)</span> <progress [value]="need.current" [max]="need.maxGoal"></progress> </div> </div> diff --git a/ufund-ui/src/app/components/need-list/need-list.component.ts b/ufund-ui/src/app/components/need-list/need-list.component.ts index 7e5c3f4..40af9f5 100644 --- a/ufund-ui/src/app/components/need-list/need-list.component.ts +++ b/ufund-ui/src/app/components/need-list/need-list.component.ts @@ -1,5 +1,5 @@ import {Component, Input, OnChanges, TemplateRef} from '@angular/core'; -import {Need} from '../../models/Need'; +import {GoalType, Need} from '../../models/Need'; @Component({ selector: 'app-need-list', @@ -25,6 +25,10 @@ export class NeedListComponent implements OnChanges { this.updateVisibleNeeds() } + getPrefix(need: Need) { + return (need.type === GoalType.MONETARY) ? "$" : ""; + } + decrementPage() { this.currentPage--; this.updateVisibleNeeds(); @@ -49,5 +53,7 @@ export class NeedListComponent implements OnChanges { this.totalPages = Math.ceil(this.needs.length / this.itemsPerPage); this.visibleNeeds = this.needs.slice(this.currentPage * this.itemsPerPage, (this.currentPage + 1) * this.itemsPerPage); } + + protected readonly GoalType = GoalType; } diff --git a/ufund-ui/src/app/components/need-page/need-page.component.css b/ufund-ui/src/app/components/need-page/need-page.component.css index 5a92ee9..f1b7f1f 100644 --- a/ufund-ui/src/app/components/need-page/need-page.component.css +++ b/ufund-ui/src/app/components/need-page/need-page.component.css @@ -31,6 +31,7 @@ .left { display: flex; flex-direction: column; + width : 50%; } .right { @@ -40,6 +41,15 @@ } } +.need-image { + width: 400px; + height: auto; + aspect-ratio: 16/9; + object-fit: cover; + border-radius: 10px; + box-shadow: rgb(0, 40, 70) 0 0 50px; +} + .urgent { font-size: 11pt; background-color: rgba(255, 165, 0, 0.27); diff --git a/ufund-ui/src/app/components/need-page/need-page.component.html b/ufund-ui/src/app/components/need-page/need-page.component.html index 592a71e..ff5990f 100644 --- a/ufund-ui/src/app/components/need-page/need-page.component.html +++ b/ufund-ui/src/app/components/need-page/need-page.component.html @@ -2,35 +2,41 @@ @if (need) { <h1>{{need.name}}</h1> <span class="needType">{{need.type}} GOAL</span> - - <img *ngIf="need.image" alt="Need image" [src]="need.image"/> - <p>{{need.description}}</p> <div class="prog"> <progress [value]="need.current" [max]="need.maxGoal"></progress> <span>This goal is <strong>{{(((need.current)*100) / (need.maxGoal)).toFixed(0)}}%</strong> complete!</span> </div> - <span><strong>Target Goal:</strong> {{need.maxGoal}}</span> - <span><strong>Amount Currently Collected:</strong> {{need.current}}</span> + <div class="split"> + <div class="left"> + <span><strong>Target Goal:</strong> {{(need.type === GoalType.MONETARY) ? "$" : ""}}{{need.maxGoal}}</span> - <span><strong>Location:</strong> {{need.location}}</span> + <span><strong>Amount Currently Collected:</strong> {{need.type.toString() == 'MONETARY' ? '$' : ''}}{{need.current}}</span> - <span><strong>Urgency: </strong> - <span *ngIf="!need.urgent">Not urgent</span> - <span *ngIf="need.urgent" class="urgent">URGENT</span> - </span> + <span><strong>Location:</strong> {{need.location}}</span> - <div *ngIf="need.filterAttributes?.length"> - <strong>Tags:</strong> - <ul style="display: flex; column-gap: 24px;"> - <li *ngFor="let tag of need?.filterAttributes"> - <p>{{tag}}</p> - </li> - </ul> + <span><strong>Urgency: </strong> + <span *ngIf="!need.urgent">Not urgent</span> + <span *ngIf="need.urgent" class="urgent">URGENT</span> + </span> + + <div *ngIf="need.filterAttributes?.length"> + <strong>Tags:</strong> + <ul style="display: flex; column-gap: 24px;"> + <li *ngFor="let tag of need?.filterAttributes"> + <p>{{tag}}</p> + </li> + </ul> + </div> + </div> + <div class="right"> + <img *ngIf="need.image" alt="Need image" class="need-image" [src]="need.image"/> + </div> </div> + <div class="actionArea"> <button *ngIf="usersService.isHelper()" (click)="add(need)" [disabled]="usersService.inBasket(usersService.getBasket() | async, need)"> <span class="icon">{{usersService.inBasket(usersService.getBasket() | async, need)? "check": "add" }}</span>Add To Basket diff --git a/ufund-ui/src/app/components/signup/signup.component.css b/ufund-ui/src/app/components/signup/signup.component.css index 429bc42..aa90e04 100644 --- a/ufund-ui/src/app/components/signup/signup.component.css +++ b/ufund-ui/src/app/components/signup/signup.component.css @@ -3,15 +3,26 @@ align-items: center; justify-content: center; height: 100%; - margin-top: -66px + margin-top: -66px; + background: rgba(0, 0, 0, .65) url("https://4kwallpapers.com/images/walls/thumbs_2t/13136.png"); + background-blend-mode: darken; + background-size: cover; } #box { display: flex; flex-direction: column; - /*max-width: 300px;*/ + max-width: 500px; gap: 10px; + backdrop-filter: blur(25px); + background-color: rgba(0, 0, 0, 0.1); + padding: 30px; + color: white; + border-radius: 5px; + border-style: solid; + border-width: 1px; + border-color: rgb(140, 140, 255); & > div { display: flex; @@ -19,6 +30,11 @@ } } +#password { + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; +} + .border { border-style: solid; border-width: 1px; @@ -34,6 +50,8 @@ width: 100%; appearance: none; overflow: hidden; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; /*margin-top: -5px;*/ } @@ -57,13 +75,10 @@ #passReq { display: flex; flex-direction: column; + margin-top: 10px; } #box > div { - display: flex; - flex-direction: row; - align-items: start; - gap: 20px; div { display: flex; diff --git a/ufund-ui/src/app/components/signup/signup.component.html b/ufund-ui/src/app/components/signup/signup.component.html index 84f15e4..ef2fc27 100644 --- a/ufund-ui/src/app/components/signup/signup.component.html +++ b/ufund-ui/src/app/components/signup/signup.component.html @@ -7,13 +7,12 @@ <div> <div> - <input placeholder="Password" type="password" (input)="validate(username.value, confirmPass.value, password.value)" #password> + <input id="password" placeholder="Password" type="password" (input)="validate(username.value, confirmPass.value, password.value)" #password> <progress [ngClass]="'color' + strength.getValue()" id="bar" [value]="strength | async" max="5"> </progress> <span *ngIf="passwordStatusText">{{passwordStatusText | async}}</span> - </div> - - <div id="passReq"> - <span *ngFor="let requirement of Object.values(passwordRequirements)" [style.color]="requirement.value ? 'green' : 'red'"><span class="icon">{{requirement.value?"check":"close"}}</span> {{requirement.title}}</span> + <div id="passReq"> + <span *ngFor="let requirement of Object.values(passwordRequirements)" [style.color]="requirement.value ? 'green' : 'red'"><span class="icon">{{requirement.value?"check":"close"}}</span> {{requirement.title}}</span> + </div> </div> </div> diff --git a/ufund-ui/src/app/components/signup/signup.component.ts b/ufund-ui/src/app/components/signup/signup.component.ts index 9c37211..2762d03 100644 --- a/ufund-ui/src/app/components/signup/signup.component.ts +++ b/ufund-ui/src/app/components/signup/signup.component.ts @@ -1,4 +1,4 @@ -import {Component} from '@angular/core'; +import {Component, ElementRef, ViewChild} from '@angular/core'; import {UsersService} from '../../services/users.service'; import {Router} from '@angular/router'; import {BehaviorSubject} from 'rxjs'; @@ -29,6 +29,7 @@ export class SignupComponent { protected ableToCreateAccount = new BehaviorSubject(false) protected passwordRequirements: PasswordRequirements = new PasswordRequirements() protected strength = new BehaviorSubject(0) + @ViewChild("username") usernameInput!: ElementRef<HTMLInputElement> constructor( protected usersService: UsersService, @@ -56,11 +57,11 @@ export class SignupComponent { validate(username: string, passConfirm:string, password: string) { this.passwordsMatch.next(false) - this.usernameStatusText.next("") + this.usernameInput.nativeElement.setAttribute("style", "") this.checkPasswordStrength(password); if (username === "") { - this.usernameStatusText.next("Username field can't be blank") + this.usernameInput.nativeElement.setAttribute("style", "border-color: #ff0000") } if (passConfirm && password === passConfirm) { @@ -105,8 +106,6 @@ export class SignupComponent { this.passwordStatusText.next("") } else if (strength == 0) { this.passwordStatusText.next("") - } else { - this.passwordStatusText.next("Password must meet requirements") } this.strength.next(strength) diff --git a/ufund-ui/src/app/components/toast/toast.component.ts b/ufund-ui/src/app/components/toast/toast.component.ts index 47fd7ff..6bbae34 100644 --- a/ufund-ui/src/app/components/toast/toast.component.ts +++ b/ufund-ui/src/app/components/toast/toast.component.ts @@ -21,7 +21,6 @@ export class ToastComponent implements OnInit{ } hide() { - console.log(this.toastDiv, typeof this.toastDiv) this.toastDiv.nativeElement.classList.add('hide') } diff --git a/ufund-ui/src/app/services/cupboard.service.ts b/ufund-ui/src/app/services/cupboard.service.ts index 694bb94..a87dee2 100644 --- a/ufund-ui/src/app/services/cupboard.service.ts +++ b/ufund-ui/src/app/services/cupboard.service.ts @@ -47,7 +47,7 @@ export class CupboardService { return this.http.delete<boolean>(`${this.url}/${id}`, this.httpOptions()) } - checkoutNeed(id: number, quantity: number) { - return this.http.put(`${this.url}/checkout`, {needID: id, amount: quantity}, this.httpOptions()) + checkoutNeed(data: {needID: number, quantity: number}[]) { + return this.http.put(`${this.url}/checkout`, data, this.httpOptions()) } } diff --git a/ufund-ui/src/app/services/users.service.ts b/ufund-ui/src/app/services/users.service.ts index d23b59b..35d080d 100644 --- a/ufund-ui/src/app/services/users.service.ts +++ b/ufund-ui/src/app/services/users.service.ts @@ -21,6 +21,15 @@ export class UsersService { }) }); + httpOptions2 = () => ({ + headers: new HttpHeaders({ + 'Content-Type': 'application/json', + "jelly-api-key": this.authService.getApiKey() + }), + responseType: "text" as "json" // don't ask me how or why this works, bc i have no clue... + // see the relevant angular bug report https://github.com/angular/angular/issues/18586 + }); + constructor( private http: HttpClient, private cupboardService: CupboardService, @@ -37,6 +46,10 @@ export class UsersService { return this.http.get<User>(`${this.url}/${id}`, this.httpOptions()) } + getCount(): Observable<number> { + return this.http.get<number>(`${this.url}/count`, this.httpOptions2()) + } + updateUser(user: User): Observable<User> { console.log(`${this.url}/${user.username}`, user, this.httpOptions) return this.http.put<User>(`${this.url}/${user.username}`, user, this.httpOptions()) |