ProfitsController.java

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

  2. import edu.ucsb.cs156.happiercows.entities.Profit;
  3. import edu.ucsb.cs156.happiercows.entities.UserCommons;
  4. import edu.ucsb.cs156.happiercows.errors.EntityNotFoundException;
  5. import edu.ucsb.cs156.happiercows.repositories.CommonsRepository;
  6. import edu.ucsb.cs156.happiercows.repositories.ProfitRepository;
  7. import edu.ucsb.cs156.happiercows.repositories.UserCommonsRepository;
  8. import io.swagger.v3.oas.annotations.tags.Tag;
  9. import io.swagger.v3.oas.annotations.Operation;
  10. import io.swagger.v3.oas.annotations.Parameter;

  11. import lombok.extern.slf4j.Slf4j;

  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.data.domain.Page;
  14. import org.springframework.data.domain.PageRequest;
  15. import org.springframework.data.domain.Sort;
  16. import org.springframework.security.access.prepost.PreAuthorize;
  17. import org.springframework.web.bind.annotation.GetMapping;
  18. import org.springframework.web.bind.annotation.RequestMapping;
  19. import org.springframework.web.bind.annotation.RequestParam;
  20. import org.springframework.web.bind.annotation.RestController;

  21. @Tag(name = "Profits")
  22. @RequestMapping("/api/profits")
  23. @RestController
  24. @Slf4j

  25. public class ProfitsController extends ApiController {

  26.     @Autowired
  27.     CommonsRepository commonsRepository;

  28.     @Autowired
  29.     UserCommonsRepository userCommonsRepository;

  30.     @Autowired
  31.     ProfitRepository profitRepository;

  32.     @Operation(summary = "Get all profits belonging to a user commons as a user via CommonsID")
  33.     @PreAuthorize("hasRole('ROLE_USER')")
  34.     @GetMapping("/all/commonsid")
  35.     public Iterable<Profit> allProfitsByCommonsId(
  36.             @Parameter(name="commonsId") @RequestParam Long commonsId
  37.     ) {
  38.         Long userId = getCurrentUser().getUser().getId();

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

  41.         Iterable<Profit> profits = profitRepository.findAllByUserCommons(userCommons);

  42.         return profits;
  43.     }

  44.     @Operation(summary = "Get all profits belonging to a user commons as a user via CommonsID")
  45.     @PreAuthorize("hasRole('ROLE_USER')")
  46.     @GetMapping("/all/commonsid/pageable")
  47.     public Page<Profit> allProfitsByCommonsIdPaged(
  48.         @Parameter(name="page") @RequestParam int page,
  49.         @Parameter(name="size") @RequestParam int size
  50.     ) {
  51.         Page<Profit> profits = profitRepository.findAll(PageRequest.of(page, size, Sort.by("timestamp").descending()));
  52.         return profits;
  53.     }
  54. }