Skip to content

Commit

Permalink
added statistics search implementation v.2
Browse files Browse the repository at this point in the history
  • Loading branch information
linubah committed Oct 9, 2023
1 parent 7361e2b commit b34622f
Show file tree
Hide file tree
Showing 11 changed files with 207 additions and 40 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.softserve.teachua.config;

import jakarta.annotation.PostConstruct;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
Expand All @@ -13,4 +17,14 @@ public class SearchStatisticsProperties {
private boolean toCache;
private String maxTime;
private int maxNumber;

@PostConstruct
public Date validateAndParseMaxTime() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return formatter.parse(this.maxTime);
} catch (ParseException | IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid date format", e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
Expand Down Expand Up @@ -155,11 +156,13 @@ public List<ClubResponse> getListClubsByUserId(@PathVariable Long id) {
*
* @return {@code Page<ClubResponse>}.
*/

@GetMapping("/clubs/search")
public Page<ClubResponse> getClubsListOfClubs(SearchClubProfile searchClubProfile,
@PageableDefault(value = CLUBS_PER_PAGE, sort = "id")
Pageable pageable) {
return clubService.getClubsBySearchParameters(searchClubProfile, pageable);
Pageable pageable,
@RequestParam(required = false) Long userId) {
return clubService.getClubsBySearchParameters(searchClubProfile, pageable, userId);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
Expand Down Expand Up @@ -47,8 +48,8 @@ public byte[] generateCenterPdfReport(@PathVariable Long centerId) {

@GetMapping(value = { "/pdf/resultsearch" }, produces = { "application/pdf" })
public byte[] generateResultSearchPdfReport(SearchClubProfile searchClubProfile,
@PageableDefault(sort = "id", value = 50) Pageable pageable) {
@PageableDefault(sort = "id", value = 50) Pageable pageable, @RequestParam(required = false) Long userId) {
return resultSearchReportGenerationService
.getPdfOutput(clubService.getClubsBySearchParameters(searchClubProfile, pageable));
.getPdfOutput(clubService.getClubsBySearchParameters(searchClubProfile, pageable, userId));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,9 @@ public SearchController(CategoryService categoryService, ClubService clubService
@GetMapping("/search")
public CombinedPossibleResponse possibleResponses(
@RequestParam @Length(max = 50) String text,
@RequestParam String cityName,
@RequestParam(required = false) Long userId
@RequestParam String cityName
) {
return CombinedPossibleResponse.builder().categories(categoryService.getPossibleCategoryByName(text))
.clubs(clubService.getPossibleClubByName(text, cityName, userId)).build();
.clubs(clubService.getPossibleClubByName(text, cityName)).build();
}
}
5 changes: 2 additions & 3 deletions src/main/java/com/softserve/teachua/service/ClubService.java
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public interface ClubService {
* @param searchClubProfile - put text of search (based on clubName, cityName & categoryName)
* @return {@code Page<ClubResponse>}
*/
Page<ClubResponse> getClubsBySearchParameters(SearchClubProfile searchClubProfile, Pageable pageable);
Page<ClubResponse> getClubsBySearchParameters(SearchClubProfile searchClubProfile, Pageable pageable, Long userId);

/**
* The method which return possible results of search by entered text.
Expand All @@ -167,10 +167,9 @@ public interface ClubService {
* The method which return possible results of search by entered text.
*
* @param text - put text of search (based on clubName & cityName)
* @param userId - put user id for collecting search statistics
* @return {@code List<SearchPossibleResponse>}
*/
List<SearchPossibleResponse> getPossibleClubByName(String text, String cityName, Long userId);
List<SearchPossibleResponse> getPossibleClubByName(String text, String cityName);

/**
* The method which return possible results of search by category and city.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import com.softserve.teachua.service.StationService;
import com.softserve.teachua.service.UserService;
import com.softserve.teachua.utils.CategoryUtil;
import com.softserve.teachua.utils.validations.QueryStringValidator;
import jakarta.validation.ValidationException;
import java.util.HashSet;
import java.util.List;
Expand Down Expand Up @@ -106,6 +107,7 @@ public class ClubServiceImpl implements ClubService, ArchiveMark<Club> {
private final ObjectMapper objectMapper;
private final ContactsStringConverter contactsStringConverter;
private FeedbackService feedbackService;
private final QueryStringValidator queryStringValidator;

@Autowired
public ClubServiceImpl(ClubRepository clubRepository, CenterRepository centerRepository,
Expand All @@ -117,7 +119,7 @@ public ClubServiceImpl(ClubRepository clubRepository, CenterRepository centerRep
CenterService centerService, SearchStatisticsService searchStatisticsService,
FeedbackRepository feedbackRepository,
ObjectMapper objectMapper, ContactsStringConverter contactsStringConverter,
ComplaintRepository complaintRepository) {
ComplaintRepository complaintRepository, QueryStringValidator queryStringValidator) {
this.clubRepository = clubRepository;
this.locationRepository = locationRepository;
this.dtoConverter = dtoConverter;
Expand All @@ -138,6 +140,7 @@ public ClubServiceImpl(ClubRepository clubRepository, CenterRepository centerRep
this.objectMapper = objectMapper;
this.contactsStringConverter = contactsStringConverter;
this.complaintRepository = complaintRepository;
this.queryStringValidator = queryStringValidator;
}

@Autowired
Expand Down Expand Up @@ -396,14 +399,22 @@ public Page<ClubResponse> getClubsWithoutCategories(Pageable pageable) {
}

@Override
public Page<ClubResponse> getClubsBySearchParameters(SearchClubProfile searchClubProfile, Pageable pageable) {
public Page<ClubResponse> getClubsBySearchParameters(SearchClubProfile searchClubProfile, Pageable pageable,
Long userId) {
log.debug("getClubsBySearchParameters ===> ");
log.debug(searchClubProfile.toString());


Page<Club> clubResponses = clubRepository.findAllByParameters(searchClubProfile.getClubName(),
searchClubProfile.getCityName(), searchClubProfile.getCategoryName(), searchClubProfile.getIsOnline(),
pageable);

if (queryStringValidator.isValid(
searchClubProfile.getClubName(),
clubResponses.getTotalElements())) {
searchStatisticsService.addToStatistics(searchClubProfile.getClubName(), userId);
}

log.debug("===find clubs : " + clubResponses.getNumberOfElements());

return new PageImpl<>(
Expand All @@ -413,10 +424,7 @@ public Page<ClubResponse> getClubsBySearchParameters(SearchClubProfile searchClu
}

@Override
public List<SearchPossibleResponse> getPossibleClubByName(String text, String cityName, Long userId) {
if (text.length() >= 4) {
searchStatisticsService.addToStatistics(text, userId);
}
public List<SearchPossibleResponse> getPossibleClubByName(String text, String cityName) {
return clubRepository.findTop3ByName(text, cityName, PageRequest.of(0, 3)).stream()
.map(category -> (SearchPossibleResponse) dtoConverter.convertToDto(category,
SearchPossibleResponse.class))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import com.softserve.teachua.repository.SearchStatisticsRepository;
import com.softserve.teachua.service.SearchStatisticsService;
import jakarta.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
Expand Down Expand Up @@ -76,11 +74,10 @@ public void deleteOldStatisticsByCount() {
}
}

@Async
@Scheduled(cron = "@weekly")
public void deleteOldStatisticsByTime() {
try {
Date date = validateDate();
Date date = searchStatisticsProperties.validateAndParseMaxTime();
List<SearchStatistics> oldRecords = searchStatisticsRepository.findAllByTimestampBefore(date);
if (oldRecords.size() > 0) {
searchStatisticsRepository.deleteAll(oldRecords);
Expand All @@ -90,16 +87,6 @@ public void deleteOldStatisticsByTime() {
log.error("Error while deleting old statistics: {}", e.getMessage());
}
}

public Date validateDate() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return formatter.parse(searchStatisticsProperties.getMaxTime());
} catch (ParseException | IllegalArgumentException e) {
log.error("Error while parsing date: {}", e.getMessage());
throw new IllegalArgumentException("Invalid date format");
}
}
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.softserve.teachua.utils.validations;

import org.springframework.stereotype.Component;

@Component
public class QueryStringValidator {
private static final int MIN_QUERY_LENGTH = 4;
private static final int MAX_QUERY_LENGTH = 50;

public boolean isValid(String queryString, long elemCount) {
if (queryString == null || queryString.trim().isEmpty()) {
return false;
}

if (elemCount < 0) {
return false;
}

if (queryString.length() < MIN_QUERY_LENGTH || queryString.length() > MAX_QUERY_LENGTH) {
return false;
}

if (!queryString.matches("^[a-zA-Z0-9\\s]+$")) {
return false;
}

return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.softserve.teachua.config;

import java.util.Date;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@EnableConfigurationProperties(SearchStatisticsProperties.class)
class SearchStatisticsPropertiesTest {

private SearchStatisticsProperties properties;

@BeforeEach
public void setUp() {
properties = new SearchStatisticsProperties();
}

@Test
void testToCache() {
properties.setToCache(true);
assertTrue(properties.isToCache());

properties.setToCache(false);
assertFalse(properties.isToCache());
}

@Test
void testMaxTime() {
properties.setMaxTime("2023-10-09 12:00:00");
assertEquals("2023-10-09 12:00:00", properties.getMaxTime());
}

@Test
void testMaxNumber() {
properties.setMaxNumber(42);
assertEquals(42, properties.getMaxNumber());
}

@Test
void testValidateAndParseMaxTimeValid() {
properties.setMaxTime("2023-10-09 12:00:00");
Date result = properties.validateAndParseMaxTime();
assertNotNull(result);
}

@Test
void testValidateAndParseMaxTimeInvalid() {
properties.setMaxTime("invalid-date-format");
assertThrows(IllegalArgumentException.class, () -> {
properties.validateAndParseMaxTime();
});
}

@Test
void testValidateAndParseMaxTimeNull() {
properties.setMaxTime("23324:323-122");
assertThrows(IllegalArgumentException.class, () -> {
properties.validateAndParseMaxTime();
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public void testDeleteOldStatisticsByTime() {
oldRecords.add(new SearchStatistics());
when(searchStatisticsProperties.getMaxTime()).thenReturn(SEARCH_DATE);

Date date = searchStatisticsService.validateDate();
Date date = searchStatisticsProperties.validateAndParseMaxTime();

when(searchStatisticsRepository.findAllByTimestampBefore(date)).thenReturn(oldRecords);

Expand All @@ -91,13 +91,4 @@ public void testDeleteOldStatisticsByTime() {
verify(searchStatisticsRepository, times(1)).deleteAll(oldRecords);
}

@Test
void testValidateDateWithInvalidFormat() {
String invalidDate = "Invalid Date String";
when(searchStatisticsProperties.getMaxTime()).thenReturn(invalidDate);

assertThrows(IllegalArgumentException.class, () -> {
searchStatisticsService.validateDate();
});
}
}
Loading

0 comments on commit b34622f

Please sign in to comment.