Advertisement
popov-aa

LocationController

Apr 1st, 2020
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.73 KB | None | 0 0
  1. package com.helan.videoafisha.backend.mvc.api;
  2.  
  3. import com.helan.videoafisha.backend.data.CascadeRemover;
  4. import com.helan.videoafisha.backend.data.record.StatisticCountRecord;
  5. import com.helan.videoafisha.backend.data.repository.*;
  6. import com.helan.videoafisha.backend.data.specifications.BookingSpecifications;
  7. import com.helan.videoafisha.backend.data.specifications.LocationSpecifications;
  8. import com.helan.videoafisha.backend.mvc.security.MemberUserDetails;
  9. import com.helan.videoafisha.entitiy.*;
  10. import lombok.extern.log4j.Log4j2;
  11. import org.modelmapper.ModelMapper;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.data.domain.Sort;
  14. import org.springframework.data.jpa.domain.Specification;
  15. import org.springframework.http.HttpStatus;
  16. import org.springframework.http.ResponseEntity;
  17. import org.springframework.security.access.prepost.PreAuthorize;
  18. import org.springframework.security.core.Authentication;
  19. import org.springframework.security.core.context.SecurityContextHolder;
  20. import org.springframework.stereotype.Controller;
  21. import org.springframework.transaction.annotation.Transactional;
  22. import org.springframework.web.bind.annotation.*;
  23.  
  24. import java.time.LocalDate;
  25. import java.util.*;
  26.  
  27. @Log4j2
  28. @Controller
  29. @RequestMapping(value = "/api/locations")
  30. public class LocationController {
  31.  
  32.     @Autowired
  33.     private ModelMapper modelMapper;
  34.  
  35.     @Autowired
  36.     private LocationRepository locationRepository;
  37.  
  38.     @Autowired
  39.     private SiteRepository siteRepository;
  40.  
  41.     @Autowired
  42.     private VideoRepository videoRepository;
  43.  
  44.     @Autowired
  45.     private CascadeRemover cascadeRemover;
  46.  
  47.     @Autowired
  48.     private LocationScheduleTimeRangeRepository locationScheduleTimeRangeRepository;
  49.  
  50.     @Autowired
  51.     private BookingRepository bookingRepository;
  52.  
  53.     @Autowired
  54.     private EntityPageBuilder entityPageBuilder;
  55.  
  56.     private static Sort SORT = Sort.by(Sort.Direction.ASC, "site.organization.title", "title");
  57.  
  58.     @PreAuthorize("hasAnyRole('CLIENT', 'ADMIN')")
  59.     @RequestMapping(method = RequestMethod.GET)
  60.     @ResponseBody
  61.     public ResponseEntity list(
  62.             @RequestParam(required = false) Optional<Integer> page,
  63.             @RequestParam(required = false) Optional<Integer> pageSize,
  64.             @RequestParam(value = "siteId", required = false) Optional<Site> site,
  65.             @RequestParam(required = false) Optional<String> search,
  66.             @RequestParam(required = false) Optional<List<Long>> filterById
  67.     ) {
  68.         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  69.         Member member = ((MemberUserDetails) authentication.getDetails()).getMember();
  70.  
  71.         Specification<Location> specification = Specification.where(null);
  72.  
  73.         if (member.getRole() != Role.Admin) {
  74.             if (site.isPresent() && !siteRepository.findByMembers(member).contains(site.get())) {
  75.                 return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
  76.             } else {
  77.                 specification = specification.and(LocationSpecifications.byMember(member));
  78.             }
  79.         }
  80.  
  81.         if (site.isPresent()) {
  82.             specification = specification.and(LocationSpecifications.bySite(site.get()));
  83.         }
  84.         if (search.isPresent()) {
  85.             specification = specification.and(LocationSpecifications.titleContainsIgnoreCase(search.get()));
  86.         }
  87.         if (filterById.isPresent()) {
  88.             specification = specification.and(LocationSpecifications.byId(filterById.get()));
  89.         }
  90.  
  91.         EntityPageBuilder.EntityPage<Location, com.helan.videoafisha.dto.backend.frontend.reactjs.locations.list.Location> entityPage = entityPageBuilder.<Location, com.helan.videoafisha.dto.backend.frontend.reactjs.locations.list.Location>build(
  92.                 locationRepository,
  93.                 SORT,
  94.                 com.helan.videoafisha.dto.backend.frontend.reactjs.locations.list.Location.class,
  95.                 page,
  96.                 pageSize,
  97.                 Optional.of(specification)
  98.         );
  99.  
  100.         if (!entityPage.getEntities().isEmpty()) {
  101.             Map<Long, Long> devicesCount = StatisticCountRecord.listToMap(locationRepository.devicesCountPerLocationByLocations(entityPage.getEntities()));
  102.             Map<Long, Long> bookingsCount = StatisticCountRecord.listToMap(locationRepository.bookingsCountPerLocationBySiteAndDateAndLocations(entityPage.getEntities(), LocalDate.now()));
  103.             for (com.helan.videoafisha.dto.backend.frontend.reactjs.locations.list.Location modelLocation : entityPage.getModelsObject()) {
  104.                 modelLocation.setDevicesCount(devicesCount.getOrDefault(modelLocation.getId(), 0L));
  105.                 modelLocation.setBookingsCount(bookingsCount.getOrDefault(modelLocation.getId(), 0L));
  106.             }
  107.         }
  108.  
  109.         return ResponseEntity.ok(entityPage.getModelsObject());
  110.     }
  111.  
  112.     @PreAuthorize("hasAnyRole('ADMIN')")
  113.     @RequestMapping(value = "/workload", method = RequestMethod.GET)
  114.     @ResponseBody
  115.     public Object workload(
  116.             @RequestParam LocalDate startDate,
  117.             @RequestParam LocalDate endDate,
  118.             @RequestParam(required = false) Optional<Integer> page,
  119.             @RequestParam(required = false) Optional<Integer> pageSize,
  120.             @RequestParam(required = false) Optional<String> search
  121.     ) {
  122.         Specification specification = Specification.where(null);
  123.         if (search.isPresent()) {
  124.             specification = specification.and(LocationSpecifications.titleContainsIgnoreCase(search.get()));
  125.         }
  126.  
  127.         EntityPageBuilder.EntityPage<Location, com.helan.videoafisha.dto.backend.frontend.reactjs.locations.workload.Location> entityPage = entityPageBuilder.<Location, com.helan.videoafisha.dto.backend.frontend.reactjs.locations.workload.Location>build(
  128.                 locationRepository,
  129.                 SORT,
  130.                 com.helan.videoafisha.dto.backend.frontend.reactjs.locations.workload.Location.class,
  131.                 page,
  132.                 pageSize,
  133.                 Optional.of(specification)
  134.         );
  135.  
  136.         Map<Long, Map<LocalDate, Long>> busyMillsByLocations = new HashMap<>();
  137.         for (Booking booking : bookingRepository.findAll(BookingSpecifications.interceptActivePeriod(startDate, endDate))) {
  138.             for (Location location : booking.getLocations()) {
  139.                 for (
  140.                         LocalDate localDate = startDate.isAfter(booking.getStartDate()) ? startDate : booking.getStartDate();
  141.                         localDate.compareTo(endDate.isBefore(booking.getEndDate()) ? endDate : booking.getEndDate()) <= 0;
  142.                         localDate = localDate.plusDays(1)
  143.                 ) {
  144.                     Map<LocalDate, Long> busyMills = busyMillsByLocations.getOrDefault(location.getId(), null);
  145.                     if (busyMills == null) {
  146.                         busyMills = new HashMap<>();
  147.                         busyMillsByLocations.put(location.getId(), busyMills);
  148.                     }
  149.                     busyMills.put(
  150.                             localDate,
  151.                             busyMills.getOrDefault(localDate, 0L) +
  152.                                     booking.getPaidVideo().getVideo().getDuration() * booking.getDemonstrationCountPerHour()
  153.                     );
  154.                 }
  155.             }
  156.         }
  157.  
  158.         Map<Long, Long> devicesCount = StatisticCountRecord.listToMap(locationRepository.devicesCountPerLocation());
  159.  
  160.         for (com.helan.videoafisha.dto.backend.frontend.reactjs.locations.workload.Location modelLocation : entityPage.getModelsObject()) {
  161.             modelLocation.setBusyMills(busyMillsByLocations.getOrDefault(modelLocation.getId(), new HashMap<>()));
  162.             modelLocation.setDevicesCount(devicesCount.getOrDefault(modelLocation.getId(), 0L));
  163.         }
  164.  
  165.         return entityPage.getModelsObject();
  166.     }
  167.  
  168.     @PreAuthorize("hasRole('ADMIN')")
  169.     @Transactional
  170.     @RequestMapping(method = RequestMethod.POST)
  171.     @ResponseBody
  172.     public com.helan.videoafisha.dto.general.Location save(@RequestBody com.helan.videoafisha.dto.backend.frontend.reactjs.locations.by_id.Location modelLocation) {
  173.         Location location = modelMapper.map(modelLocation, Location.class);
  174.         if (modelLocation.getId() != null) {
  175.             location.setScheduleTimeRanges(locationRepository.getOne(modelLocation.getId()).getScheduleTimeRanges());
  176.         }
  177.         locationRepository.save(location);
  178.         return modelMapper.map(location, com.helan.videoafisha.dto.general.Location.class);
  179.     }
  180.  
  181.     @PreAuthorize("hasRole('ADMIN')")
  182.     @Transactional
  183.     @RequestMapping(value = "/{id}/geolocation", method = RequestMethod.POST)
  184.     @ResponseBody
  185.     public com.helan.videoafisha.dto.general.Location saveGeolocation(
  186.             @PathVariable("id") Long id,
  187.             @RequestBody com.helan.videoafisha.dto.backend.frontend.reactjs.locations.with_geolocation.Geolocation modelGeolocation) {
  188.         Location location = locationRepository.getOne(id);
  189.         Geolocation geolocation = modelMapper.map(modelGeolocation, Geolocation.class);
  190.         location.setGeolocation(geolocation);
  191.         locationRepository.save(location);
  192.         return modelMapper.map(location, com.helan.videoafisha.dto.general.Location.class);
  193.     }
  194.  
  195.     @PreAuthorize("hasAnyRole('ADMIN', 'CLIENT')")
  196.     @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  197.     @ResponseBody
  198.     public ResponseEntity byId(
  199.             @PathVariable("id") Long id,
  200.             @RequestParam(required = false, defaultValue = "") String variant) {
  201.         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  202.         Member member = ((MemberUserDetails) authentication.getDetails()).getMember();
  203.  
  204.         Location location = locationRepository.getOne(id);
  205.         if (member.getRole() == Role.Client && !siteRepository.findByMembers(member).contains(location.getSite())) {
  206.             return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
  207.         } else {
  208.             Class clazz;
  209.             switch (variant) {
  210.                 case "with_geolocation":
  211.                     clazz = com.helan.videoafisha.dto.backend.frontend.reactjs.locations.with_geolocation.Location.class;
  212.                     break;
  213.                 case "":
  214.                     clazz = com.helan.videoafisha.dto.backend.frontend.reactjs.locations.by_id.Location.class;
  215.                     break;
  216.                 default:
  217.                     throw new RuntimeException(String.format("Unknown DTO variant %s", variant));
  218.             }
  219.             return ResponseEntity.ok(modelMapper.map(location, clazz));
  220.         }
  221.     }
  222.  
  223.     @PreAuthorize("hasRole('ADMIN')")
  224.     @Transactional
  225.     @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
  226.     public ResponseEntity delete(@PathVariable("id") Long id) {
  227.         cascadeRemover.removeLocation(locationRepository.getOne(id), new HashSet());
  228.         return ResponseEntity.ok().build();
  229.     }
  230. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement