CommonsController.java

  1. package edu.ucsb.cs156.happiercows.controllers;

  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import edu.ucsb.cs156.happiercows.entities.Commons;
  5. import edu.ucsb.cs156.happiercows.entities.CommonsPlus;
  6. import edu.ucsb.cs156.happiercows.entities.User;
  7. import edu.ucsb.cs156.happiercows.entities.UserCommons;
  8. import edu.ucsb.cs156.happiercows.errors.EntityNotFoundException;
  9. import edu.ucsb.cs156.happiercows.models.CreateCommonsParams;
  10. import edu.ucsb.cs156.happiercows.models.HealthUpdateStrategyList;
  11. import edu.ucsb.cs156.happiercows.repositories.CommonsRepository;
  12. import edu.ucsb.cs156.happiercows.repositories.UserCommonsRepository;
  13. import edu.ucsb.cs156.happiercows.strategies.CowHealthUpdateStrategies;
  14. import io.swagger.v3.oas.annotations.tags.Tag;
  15. import io.swagger.v3.oas.annotations.Operation;
  16. import io.swagger.v3.oas.annotations.Parameter;
  17. import org.springframework.beans.factory.annotation.Value;
  18. import lombok.extern.slf4j.Slf4j;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.http.HttpStatus;
  21. import org.springframework.http.ResponseEntity;
  22. import org.springframework.security.access.prepost.PreAuthorize;
  23. import org.springframework.web.bind.annotation.*;
  24. import edu.ucsb.cs156.happiercows.services.CommonsPlusBuilderService;


  25. import java.util.Optional;


  26. @Slf4j
  27. @Tag(name = "Commons")
  28. @RequestMapping("/api/commons")
  29. @RestController
  30. public class CommonsController extends ApiController {
  31.     @Autowired
  32.     private CommonsRepository commonsRepository;

  33.     @Autowired
  34.     private UserCommonsRepository userCommonsRepository;

  35.     @Autowired
  36.     ObjectMapper mapper;

  37.     @Autowired
  38.     CommonsPlusBuilderService commonsPlusBuilderService;

  39.     @Value("${app.commons.default.startingBalance}")
  40.     private double defaultStartingBalance;

  41.     @Value("${app.commons.default.cowPrice}")
  42.     private double defaultCowPrice;

  43.     @Value("${app.commons.default.milkPrice}")
  44.     private double defaultMilkPrice;

  45.     @Value("${app.commons.default.degradationRate}")
  46.     private double defaultDegradationRate;

  47.     @Value("${app.commons.default.carryingCapacity}")
  48.     private int defaultCarryingCapacity;

  49.     @Value("${app.commons.default.capacityPerUser}")
  50.     private int defaultCapacityPerUser;

  51.     @Value("${app.commons.default.aboveCapacityHealthUpdateStrategy}")
  52.     private String defaultAboveCapacityHealthUpdateStrategy;

  53.     @Value("${app.commons.default.belowCapacityHealthUpdateStrategy}")
  54.     private String defaultBelowCapacityHealthUpdateStrategy;

  55.     @Operation(summary = "Get default common values")
  56.     @GetMapping("/defaults")
  57.     public ResponseEntity<Commons> getDefaultCommons() throws JsonProcessingException {
  58.         log.info("getDefaultCommons()...");

  59.         Commons defaultCommons = Commons.builder()
  60.                 .startingBalance(defaultStartingBalance)
  61.                 .cowPrice(defaultCowPrice)
  62.                 .milkPrice(defaultMilkPrice)
  63.                 .degradationRate(defaultDegradationRate)
  64.                 .carryingCapacity(defaultCarryingCapacity)
  65.                 .capacityPerUser(defaultCapacityPerUser)
  66.                 .aboveCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(defaultAboveCapacityHealthUpdateStrategy))
  67.                 .belowCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(defaultBelowCapacityHealthUpdateStrategy))
  68.                 .build();

  69.         return ResponseEntity.ok().body(defaultCommons);
  70.     }

  71.     @Operation(summary = "Get a list of all commons")
  72.     @GetMapping("/all")
  73.     public ResponseEntity<String> getCommons() throws JsonProcessingException {
  74.         log.info("getCommons()...");
  75.         Iterable<Commons> commons = commonsRepository.findAll();
  76.         String body = mapper.writeValueAsString(commons);
  77.         return ResponseEntity.ok().body(body);
  78.     }

  79.     @Operation(summary = "Get a list of all commons and number of cows/users")
  80.     @GetMapping("/allplus")
  81.     public ResponseEntity<String> getCommonsPlus() throws JsonProcessingException {
  82.         log.info("getCommonsPlus()...");
  83.         Iterable<Commons> commonsListIter = commonsRepository.findAll();

  84.         // convert Iterable to List for the purposes of using a Java Stream & lambda
  85.         // below
  86.         Iterable<CommonsPlus> commonsPlusList = commonsPlusBuilderService.convertToCommonsPlus(commonsListIter);

  87.         String body = mapper.writeValueAsString(commonsPlusList);
  88.         return ResponseEntity.ok().body(body);
  89.     }

  90.     @Operation(summary = "Get the number of cows/users in a commons")
  91.     @PreAuthorize("hasRole('ROLE_USER')")
  92.     @GetMapping("/plus")
  93.     public CommonsPlus getCommonsPlusById(
  94.             @Parameter(name="id") @RequestParam long id) throws JsonProcessingException {
  95.                 CommonsPlus commonsPlus = commonsPlusBuilderService.toCommonsPlus(commonsRepository.findById(id)
  96.                 .orElseThrow(() -> new EntityNotFoundException(Commons.class, id)));

  97.         return commonsPlus;
  98.     }

  99.     @Operation(summary = "Update a commons")
  100.     @PreAuthorize("hasRole('ROLE_ADMIN')")
  101.     @PutMapping("/update")
  102.     public ResponseEntity<String> updateCommons(
  103.             @Parameter(name="id") @RequestParam long id,
  104.             @Parameter(name="request body") @RequestBody CreateCommonsParams params
  105.     ) {
  106.         Optional<Commons> existing = commonsRepository.findById(id);

  107.         Commons updated;
  108.         HttpStatus status;

  109.         if (existing.isPresent()) {
  110.             updated = existing.get();
  111.             status = HttpStatus.NO_CONTENT;
  112.         } else {
  113.             updated = new Commons();
  114.             status = HttpStatus.CREATED;
  115.         }

  116.         updated.setName(params.getName());
  117.         updated.setCowPrice(params.getCowPrice());
  118.         updated.setMilkPrice(params.getMilkPrice());
  119.         updated.setStartingBalance(params.getStartingBalance());
  120.         updated.setStartingDate(params.getStartingDate());
  121.         updated.setLastDate(params.getLastDate());
  122.         updated.setShowLeaderboard(params.getShowLeaderboard());
  123.         updated.setShowChat(params.getShowChat());
  124.         updated.setDegradationRate(params.getDegradationRate());
  125.         updated.setCapacityPerUser(params.getCapacityPerUser());
  126.         updated.setCarryingCapacity(params.getCarryingCapacity());
  127.         if (params.getAboveCapacityHealthUpdateStrategy() != null) {
  128.             updated.setAboveCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getAboveCapacityHealthUpdateStrategy()));
  129.         }
  130.         if (params.getBelowCapacityHealthUpdateStrategy() != null) {
  131.             updated.setBelowCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getBelowCapacityHealthUpdateStrategy()));
  132.         }

  133.         if (params.getDegradationRate() < 0) {
  134.             throw new IllegalArgumentException("Degradation Rate cannot be negative");
  135.         }

  136.         // Reference: frontend/src/main/components/Commons/CommonsForm.js
  137.         if (params.getName().equals("")) {
  138.             throw new IllegalArgumentException("Name cannot be empty");
  139.         }

  140.         if (params.getCowPrice() < 0.01) {
  141.             throw new IllegalArgumentException("Cow Price cannot be less than 0.01");
  142.         }

  143.         if (params.getMilkPrice() < 0.01) {
  144.             throw new IllegalArgumentException("Milk Price cannot be less than 0.01");
  145.         }

  146.         if (params.getStartingBalance() < 0) {
  147.             throw new IllegalArgumentException("Starting Balance cannot be negative");
  148.         }

  149.         if (params.getCarryingCapacity() < 1) {
  150.             throw new IllegalArgumentException("Carrying Capacity cannot be less than 1");
  151.         }
  152.         commonsRepository.save(updated);

  153.         return ResponseEntity.status(status).build();
  154.     }

  155.     @Operation(summary = "Get a specific commons")
  156.     @PreAuthorize("hasRole('ROLE_USER')")
  157.     @GetMapping("")
  158.     public Commons getCommonsById(
  159.             @Parameter(name="id") @RequestParam Long id) throws JsonProcessingException {

  160.         Commons commons = commonsRepository.findById(id)
  161.                 .orElseThrow(() -> new EntityNotFoundException(Commons.class, id));

  162.         return commons;
  163.     }

  164.     @Operation(summary = "Create a new commons")
  165.     @PreAuthorize("hasRole('ROLE_ADMIN')")
  166.     @PostMapping(value = "/new", produces = "application/json")
  167.     public ResponseEntity<String> createCommons(
  168.             @Parameter(name="request body") @RequestBody CreateCommonsParams params
  169.     ) throws JsonProcessingException {

  170.         var builder = Commons.builder()
  171.                 .name(params.getName())
  172.                 .cowPrice(params.getCowPrice())
  173.                 .milkPrice(params.getMilkPrice())
  174.                 .startingBalance(params.getStartingBalance())
  175.                 .startingDate(params.getStartingDate())
  176.                 .lastDate(params.getLastDate())
  177.                 .degradationRate(params.getDegradationRate())
  178.                 .showLeaderboard(params.getShowLeaderboard())
  179.                 .showChat(params.getShowChat())
  180.                 .capacityPerUser(params.getCapacityPerUser())
  181.                 .carryingCapacity(params.getCarryingCapacity());

  182.         // ok to set null values for these, so old backend still works
  183.         if (params.getAboveCapacityHealthUpdateStrategy() != null) {
  184.             builder.aboveCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getAboveCapacityHealthUpdateStrategy()));
  185.         }
  186.         if (params.getBelowCapacityHealthUpdateStrategy() != null) {
  187.             builder.belowCapacityHealthUpdateStrategy(CowHealthUpdateStrategies.valueOf(params.getBelowCapacityHealthUpdateStrategy()));
  188.         }

  189.         Commons commons = builder.build();

  190.         // Reference: frontend/src/main/components/Commons/CommonsForm.js
  191.         if (params.getName().equals("")) {
  192.             throw new IllegalArgumentException("Name cannot be empty");
  193.         }

  194.         if (params.getCowPrice() < 0.01) {
  195.             throw new IllegalArgumentException("Cow Price cannot be less than 0.01");
  196.         }

  197.         if (params.getMilkPrice() < 0.01) {
  198.             throw new IllegalArgumentException("Milk Price cannot be less than 0.01");
  199.         }

  200.         if (params.getStartingBalance() < 0) {
  201.             throw new IllegalArgumentException("Starting Balance cannot be negative");
  202.         }

  203.         // throw exception for degradation rate
  204.         if (params.getDegradationRate() < 0) {
  205.             throw new IllegalArgumentException("Degradation Rate cannot be negative");
  206.         }

  207.         if (params.getCarryingCapacity() < 1) {
  208.             throw new IllegalArgumentException("Carrying Capacity cannot be less than 1");
  209.         }

  210.         Commons saved = commonsRepository.save(commons);
  211.         String body = mapper.writeValueAsString(saved);

  212.         return ResponseEntity.ok().body(body);
  213.     }


  214.     @Operation(summary = "List all cow health update strategies")
  215.     @PreAuthorize("hasRole('ROLE_USER')")
  216.     @GetMapping("/all-health-update-strategies")
  217.     public ResponseEntity<String> listCowHealthUpdateStrategies() throws JsonProcessingException {
  218.         var result = HealthUpdateStrategyList.create();
  219.         String body = mapper.writeValueAsString(result);
  220.         return ResponseEntity.ok().body(body);
  221.     }

  222.     @Operation(summary = "Join a commons")
  223.     @PreAuthorize("hasRole('ROLE_USER')")
  224.     @PostMapping(value = "/join", produces = "application/json")
  225.     public ResponseEntity<String> joinCommon(
  226.             @Parameter(name="commonsId") @RequestParam Long commonsId) throws Exception {

  227.         User u = getCurrentUser().getUser();
  228.         Long userId = u.getId();
  229.         String username = u.getFullName();

  230.         Commons joinedCommons = commonsRepository.findById(commonsId)
  231.                 .orElseThrow(() -> new EntityNotFoundException(Commons.class, commonsId));
  232.         Optional<UserCommons> userCommonsLookup = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId);

  233.         if (userCommonsLookup.isPresent()) {
  234.             // user is already a member of this commons
  235.             String body = mapper.writeValueAsString(joinedCommons);
  236.             return ResponseEntity.ok().body(body);
  237.         }

  238.         UserCommons uc = UserCommons.builder()
  239.                 .user(u)
  240.                 .commons(joinedCommons)
  241.                 .username(username)
  242.                 .totalWealth(joinedCommons.getStartingBalance())
  243.                 .numOfCows(0)
  244.                 .cowHealth(100)
  245.                 .cowsBought(0)
  246.                 .cowsSold(0)
  247.                 .cowDeaths(0)
  248.                 .build();

  249.         userCommonsRepository.save(uc);

  250.         String body = mapper.writeValueAsString(joinedCommons);
  251.         return ResponseEntity.ok().body(body);
  252.     }

  253.     @Operation(summary = "Delete a Commons")
  254.     @PreAuthorize("hasRole('ROLE_ADMIN')")
  255.     @DeleteMapping("")
  256.     public Object deleteCommons(
  257.             @Parameter(name="id") @RequestParam Long id) {
  258.        
  259.         Iterable<UserCommons> userCommons = userCommonsRepository.findByCommonsId(id);

  260.         for (UserCommons commons : userCommons) {
  261.             userCommonsRepository.delete(commons);
  262.         }

  263.         commonsRepository.findById(id)
  264.                 .orElseThrow(() -> new EntityNotFoundException(Commons.class, id));

  265.         commonsRepository.deleteById(id);

  266.         String responseString = String.format("commons with id %d deleted", id);
  267.         return genericMessage(responseString);

  268.     }

  269.     @Operation(summary="Delete a user from a commons")
  270.     @PreAuthorize("hasRole('ROLE_ADMIN')")
  271.     @DeleteMapping("/{commonsId}/users/{userId}")
  272.     public Object deleteUserFromCommon(@PathVariable("commonsId") Long commonsId,
  273.                                        @PathVariable("userId") Long userId) throws Exception {

  274.         UserCommons userCommons = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId)
  275.                 .orElseThrow(() -> new EntityNotFoundException(
  276.                         UserCommons.class, "commonsId", commonsId, "userId", userId)
  277.                 );

  278.         userCommonsRepository.delete(userCommons);

  279.         String responseString = String.format("user with id %d deleted from commons with id %d, %d users remain", userId, commonsId, commonsRepository.getNumUsers(commonsId).orElse(0));

  280.         return genericMessage(responseString);
  281.     }

  282.    
  283. }