UserCommonsController.java

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

  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;

  4. import org.springframework.beans.factory.annotation.Autowired;

  5. import org.springframework.security.access.prepost.PreAuthorize;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.bind.annotation.RestController;

  10. import edu.ucsb.cs156.happiercows.repositories.UserCommonsRepository;
  11. import edu.ucsb.cs156.happiercows.repositories.CommonsRepository;
  12. import edu.ucsb.cs156.happiercows.entities.User;
  13. import edu.ucsb.cs156.happiercows.entities.UserCommons;
  14. import edu.ucsb.cs156.happiercows.entities.Commons;
  15. import edu.ucsb.cs156.happiercows.errors.EntityNotFoundException;
  16. import edu.ucsb.cs156.happiercows.errors.NoCowsException;
  17. import edu.ucsb.cs156.happiercows.errors.NotEnoughMoneyException;

  18. import io.swagger.v3.oas.annotations.tags.Tag;
  19. import io.swagger.v3.oas.annotations.Operation;
  20. import io.swagger.v3.oas.annotations.Parameter;

  21. import org.springframework.http.ResponseEntity;
  22. import org.springframework.web.bind.annotation.PutMapping;

  23. @Tag(name = "User Commons")
  24. @RequestMapping("/api/usercommons")
  25. @RestController
  26. public class UserCommonsController extends ApiController {

  27.   @Autowired
  28.   private UserCommonsRepository userCommonsRepository;

  29.   @Autowired
  30.   private CommonsRepository commonsRepository;

  31.   @Autowired
  32.   ObjectMapper mapper;

  33.   @Operation(summary = "Get a specific user commons (admin only)")
  34.   @PreAuthorize("hasRole('ROLE_ADMIN')")
  35.   @GetMapping("")
  36.   public UserCommons getUserCommonsById(
  37.       @Parameter(name="userId") @RequestParam Long userId,
  38.       @Parameter(name="commonsId") @RequestParam Long commonsId) throws JsonProcessingException {

  39.     UserCommons userCommons = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId)
  40.         .orElseThrow(
  41.             () -> new EntityNotFoundException(UserCommons.class, "commonsId", commonsId, "userId", userId));
  42.     return userCommons;
  43.   }

  44.   @Operation(summary = "Get a user commons for current user")
  45.   @PreAuthorize("hasRole('ROLE_USER')")
  46.   @GetMapping("/forcurrentuser")
  47.   public UserCommons getUserCommonsById(
  48.       @Parameter(name="commonsId") @RequestParam Long commonsId) throws JsonProcessingException {

  49.     User u = getCurrentUser().getUser();
  50.     Long userId = u.getId();
  51.     UserCommons userCommons = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId)
  52.         .orElseThrow(
  53.             () -> new EntityNotFoundException(UserCommons.class, "commonsId", commonsId, "userId", userId));
  54.     return userCommons;
  55.   }

  56.   @Operation(summary = "Buy a cow, totalWealth updated")
  57.   @PreAuthorize("hasRole('ROLE_USER')")
  58.   @PutMapping("/buy")
  59.   public ResponseEntity<String> putUserCommonsByIdBuy(
  60.           @Parameter(name="commonsId") @RequestParam Long commonsId,
  61.           @Parameter(name="numCows") @RequestParam int numCows) throws NotEnoughMoneyException, JsonProcessingException{

  62.         User u = getCurrentUser().getUser();
  63.         Long userId = u.getId();

  64.         Commons commons = commonsRepository.findById(commonsId).orElseThrow(
  65.           ()->new EntityNotFoundException(Commons.class, commonsId));
  66.         UserCommons userCommons = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId)
  67.         .orElseThrow(
  68.             () -> new EntityNotFoundException(UserCommons.class, "commonsId", commonsId, "userId", userId));

  69.         if(userCommons.getTotalWealth() >= (commons.getCowPrice() * numCows)){
  70.           userCommons.setTotalWealth(userCommons.getTotalWealth() - (commons.getCowPrice() * numCows));
  71.           userCommons.setNumOfCows(userCommons.getNumOfCows() + numCows);
  72.           userCommons.setCowsBought(userCommons.getCowsBought() + numCows);
  73.         }
  74.         else{
  75.           throw new NotEnoughMoneyException("You need more money!");
  76.         }
  77.         userCommonsRepository.save(userCommons);

  78.         String body = mapper.writeValueAsString(userCommons);
  79.         return ResponseEntity.ok().body(body);
  80.     }

  81.   @Operation(summary = "Sell a cow, totalWealth updated")
  82.   @PreAuthorize("hasRole('ROLE_USER')")
  83.   @PutMapping("/sell")
  84.   public ResponseEntity<String> putUserCommonsByIdSell(
  85.           @Parameter(name="commonsId") @RequestParam Long commonsId,
  86.           @Parameter(name="numCows") @RequestParam int numCows) throws NoCowsException, JsonProcessingException {
  87.         User u = getCurrentUser().getUser();
  88.         Long userId = u.getId();

  89.         Commons commons = commonsRepository.findById(commonsId).orElseThrow(
  90.           ()->new EntityNotFoundException(Commons.class, commonsId));
  91.         UserCommons userCommons = userCommonsRepository.findByCommonsIdAndUserId(commonsId, userId)
  92.         .orElseThrow(
  93.             () -> new EntityNotFoundException(UserCommons.class, "commonsId", commonsId, "userId", userId));


  94.         if(userCommons.getNumOfCows() >= numCows ){
  95.           double cowValue = commons.getCowPrice() * userCommons.getCowHealth() / 100;
  96.           userCommons.setTotalWealth(userCommons.getTotalWealth() + (cowValue * numCows));
  97.           userCommons.setNumOfCows(userCommons.getNumOfCows() - numCows);
  98.           userCommons.setCowsSold(userCommons.getCowsSold() + numCows);
  99.         }
  100.         else{
  101.           throw new NoCowsException("You do not have enough cows to sell!");
  102.         }
  103.         userCommonsRepository.save(userCommons);

  104.         String body = mapper.writeValueAsString(userCommons);
  105.         return ResponseEntity.ok().body(body);
  106.     }

  107.    

  108.     @Operation(summary = "Get all user commons for a specific commons")
  109.     @PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
  110.     @GetMapping("/commons/all")
  111.     public  ResponseEntity<String> getUsersCommonsByCommonsId(
  112.         @Parameter(name="commonsId") @RequestParam Long commonsId) throws JsonProcessingException {
  113.       Iterable<UserCommons> uc = userCommonsRepository.findByCommonsId(commonsId);
  114.      
  115.    
  116.     String body = mapper.writeValueAsString(uc);
  117.     return ResponseEntity.ok().body(body);
  118.   }

  119. }