Skip to content

Commit

Permalink
fix(support): fixing merge overwrite (#475)
Browse files Browse the repository at this point in the history
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Derek Roberts <derek.roberts@gmail.com>
  • Loading branch information
3 people authored Nov 19, 2024
1 parent 5f3a165 commit 337c414
Show file tree
Hide file tree
Showing 30 changed files with 1,140 additions and 1,291 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pr-open.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
name: Initialize
if: "!github.event.pull_request.head.repo.fork"
outputs:
route: ${{ github.event.number }}
route: ${{ steps.route.outputs.route }}
runs-on: ubuntu-latest
permissions:
pull-requests: write
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class OpeningSearchFiltersDto {

@Setter
private String requestUserId;
private List<String> openingIds;
private List<Long> openingIds;

/** Creates an instance of the search opening filter dto. */
public OpeningSearchFiltersDto(
Expand Down Expand Up @@ -96,7 +96,7 @@ public OpeningSearchFiltersDto(

// Create a constructor with only the List<String> openingIds
public OpeningSearchFiltersDto(
List<String> openingIds) {
List<Long> openingIds) {
this.orgUnit = new ArrayList<>();
this.category = new ArrayList<>();
this.statusList = new ArrayList<>();
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
Expand Down Expand Up @@ -398,7 +399,8 @@ private String createNativeSqlQuery(OpeningSearchFiltersDto filtersDto) {
/* Filters */
// List of openings from the openingIds of the filterDto object for the recent openings
if (filtersDto.hasValue(SilvaOracleConstants.OPENING_IDS)) {
String openingIds = String.join(",", filtersDto.getOpeningIds());
String openingIds = filtersDto.getOpeningIds().stream().map(String::valueOf).collect(
Collectors.joining(","));
log.info("Filter for openingIds detected! openingIds={}", openingIds);
builder.append(String.format("AND o.OPENING_ID IN (%s) ", openingIds));
}
Expand Down Expand Up @@ -450,11 +452,7 @@ private String createNativeSqlQuery(OpeningSearchFiltersDto filtersDto) {
// 5. Submitted to FRPA
if (filtersDto.hasValue(SilvaOracleConstants.SUBMITTED_TO_FRPA)) {
Boolean value = filtersDto.getSubmittedToFrpa();
if (Boolean.FALSE.equals(value)) {
log.info(
"Filter submitted to FRPA detected! submitted={}", filtersDto.getSubmittedToFrpa());
builder.append("AND sra.SILV_RELIEF_APPLICATION_ID IS NULL ");
} else {
if (Boolean.TRUE.equals(value)) {
log.info(
"Filter submitted to FRPA detected! submitted={}", filtersDto.getSubmittedToFrpa());
builder.append("AND sra.SILV_RELIEF_APPLICATION_ID IS NOT NULL ");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,56 +50,6 @@ public class OpeningService {

private final ForestClientApiProvider forestClientApiProvider;

/**
* Gets all recent openings for the Home Screen.
*
* @param pagination A {@link PaginationParameters} with pagination settings.
* @return {@link List} of {@link RecentOpeningDto} containing all recent openings for that user.
*/
public PaginatedResult<RecentOpeningDto> getRecentOpeningsCurrentUser(
PaginationParameters pagination) {
log.info(
"Getting recent openings to logged user with page index {} and page size {}",
pagination.page(),
pagination.perPage());

if (pagination.perPage() > SilvaConstants.MAX_PAGE_SIZE) {
throw new MaxPageSizeException(SilvaConstants.MAX_PAGE_SIZE);
}

String entryUserId = loggedUserService.getLoggedUserId();

// Openings
Pageable pageable =
PageRequest.of(
pagination.page(), pagination.perPage(), Sort.by("updateTimestamp").descending());
Page<OpeningEntity> openingPage = openingRepository.findAllByEntryUserId(entryUserId, pageable);

PaginatedResult<RecentOpeningDto> paginatedResult = new PaginatedResult<>();
paginatedResult.setPageIndex(pagination.page());
paginatedResult.setPerPage(pagination.perPage());

if (openingPage.getContent().isEmpty()) {
log.info("No recent openings for this user given page index and size!");
paginatedResult.setData(List.of());
paginatedResult.setTotalPages(0);
paginatedResult.setHasNextPage(false);
return paginatedResult;
}

// Cut Block Open Admin
List<Long> openingIds = openingPage.getContent().stream().map(OpeningEntity::getId).toList();
List<CutBlockOpenAdminEntity> cutBlocks =
cutBlockOpenAdminService.findAllByOpeningIdIn(openingIds);

List<RecentOpeningDto> list = createDtoFromEntity(openingPage.getContent(), cutBlocks);
paginatedResult.setData(list);
paginatedResult.setTotalPages(openingPage.getTotalPages());
paginatedResult.setHasNextPage(openingPage.hasNext());

return paginatedResult;
}

/**
* Get recent openings given the opening creation date.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
@Builder
public record UserRecentOpeningDto(
String userId,
String openingId,
Long openingId,
LocalDateTime lastViewed
) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public ResponseEntity<PaginatedResult<OpeningSearchResponseDto>> getUserRecentOp
@PutMapping("/{openingId}")
@ResponseStatus(HttpStatus.ACCEPTED)
public void recordUserViewedOpening(
@PathVariable String openingId) {
@PathVariable Long openingId) {
// Store the opening and return the DTO
userRecentOpeningService.storeViewedOpening(openingId);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.With;

import java.time.LocalDateTime;

@Data
@NoArgsConstructor
@AllArgsConstructor
Expand All @@ -31,7 +30,7 @@ public class UserRecentOpeningEntity {
private String userId;

@Column(name = "opening_id", nullable = false)
private String openingId;
private Long openingId;

@Column(name = "last_viewed", nullable = false)
private LocalDateTime lastViewed;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
package ca.bc.gov.restapi.results.postgres.repository;

import ca.bc.gov.restapi.results.postgres.entity.UserRecentOpeningEntity;
import java.util.List;

import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRecentOpeningRepository extends JpaRepository<UserRecentOpeningEntity, Long> {
UserRecentOpeningEntity findByUserIdAndOpeningId(String userId, String openingId);
Optional<UserRecentOpeningEntity> findByUserIdAndOpeningId(String userId, Long openingId);
// Add a method to fetch recent openings for a user with a limit and sorting by last_viewed in descending order
Page<UserRecentOpeningEntity> findByUserIdOrderByLastViewedDesc(String userId, Pageable pageable);
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
package ca.bc.gov.restapi.results.postgres.service;

import ca.bc.gov.restapi.results.common.exception.OpeningNotFoundException;
import ca.bc.gov.restapi.results.common.pagination.PaginatedResult;
import ca.bc.gov.restapi.results.common.pagination.PaginationParameters;
import ca.bc.gov.restapi.results.common.security.LoggedUserService;
import ca.bc.gov.restapi.results.oracle.dto.OpeningSearchFiltersDto;
import ca.bc.gov.restapi.results.oracle.dto.OpeningSearchResponseDto;
import ca.bc.gov.restapi.results.oracle.repository.OpeningRepository;
import ca.bc.gov.restapi.results.oracle.service.OpeningService;
import ca.bc.gov.restapi.results.postgres.dto.UserRecentOpeningDto;
import ca.bc.gov.restapi.results.postgres.entity.UserRecentOpeningEntity;
import ca.bc.gov.restapi.results.postgres.repository.UserRecentOpeningRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import jakarta.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
Expand All @@ -31,37 +33,40 @@ public class UserRecentOpeningService {
private final LoggedUserService loggedUserService;
private final UserRecentOpeningRepository userRecentOpeningRepository;
private final OpeningService openingService;
private final OpeningRepository openingRepository;

/**
* Stores the opening viewed by the user and returns the DTO.
*
* @param openingId The ID of the opening viewed by the user.
* @return A DTO with userId, openingId, and lastViewed timestamp.
*/
public UserRecentOpeningDto storeViewedOpening(String openingId) {
String userId = loggedUserService.getLoggedUserId();
LocalDateTime lastViewed = LocalDateTime.now();

// Verify that the openingId String contains numbers only and no spaces
if (!openingId.matches("^[0-9]*$")) {
@Transactional
public UserRecentOpeningDto storeViewedOpening(Long openingId) {
log.info("Adding opening ID {} as recently viewed for user {}", openingId,
loggedUserService.getLoggedUserId());

if(openingId == null) {
log.info("Opening ID is null");
throw new IllegalArgumentException("Opening ID must contain numbers only!");
}

// Check if the user has already viewed this opening
UserRecentOpeningEntity existingEntity = userRecentOpeningRepository.findByUserIdAndOpeningId(userId, openingId);

if (existingEntity != null) {
// Update the last viewed timestamp for the existing record
existingEntity.setLastViewed(lastViewed);
userRecentOpeningRepository.save(existingEntity); // Save the updated entity
} else {
// Create a new entity if this openingId is being viewed for the first time
UserRecentOpeningEntity newEntity = new UserRecentOpeningEntity(null, userId, openingId, lastViewed);
userRecentOpeningRepository.save(newEntity); // Save the new entity
if (!openingRepository.existsById(openingId)) {
log.info("Opening ID not found: {}", openingId);
throw new OpeningNotFoundException();
}

LocalDateTime lastViewed = LocalDateTime.now();

userRecentOpeningRepository.saveAndFlush(
userRecentOpeningRepository
.findByUserIdAndOpeningId(loggedUserService.getLoggedUserId(), openingId)
.map(entity -> entity.withLastViewed(lastViewed))
.orElse(
new UserRecentOpeningEntity(null,loggedUserService.getLoggedUserId(),openingId,lastViewed)
)
);

// Return the DTO
return new UserRecentOpeningDto(userId, openingId, lastViewed);
return new UserRecentOpeningDto(
loggedUserService.getLoggedUserId(),
openingId,
lastViewed
);
}

/**
Expand All @@ -79,29 +84,33 @@ public PaginatedResult<OpeningSearchResponseDto> getAllRecentOpeningsForUser(int
.findByUserIdOrderByLastViewedDesc(userId, pageable);

// Extract opening IDs as String
Map<String,LocalDateTime> openingIds = recentOpenings.getContent().stream()
Map<Long, LocalDateTime> openingIds = recentOpenings.getContent().stream()
.collect(Collectors.toMap(UserRecentOpeningEntity::getOpeningId, UserRecentOpeningEntity::getLastViewed));
log.info("User with the userId {} has the following openindIds {}", userId, openingIds);
log.info("User with the userId {} has the following openingIds {}", userId, openingIds);

if (openingIds.isEmpty()) {
return new PaginatedResult<>();
// Ensure an empty data list instead of null
return new PaginatedResult<OpeningSearchResponseDto>()
.withData(Collections.emptyList());
}

PaginatedResult<OpeningSearchResponseDto> pageResult =
openingService
.openingSearch(
new OpeningSearchFiltersDto(new ArrayList<>(openingIds.keySet())),
new PaginationParameters(0, 10)
);

return pageResult
.withData(
pageResult
.getData()
.stream()
.peek(result -> result.setLastViewDate(openingIds.get(result.getOpeningId().toString())))
.map(result -> result.withLastViewDate(openingIds.get(result.getOpeningId().longValue())))
.sorted(Comparator.comparing(OpeningSearchResponseDto::getLastViewDate).reversed())
.collect(Collectors.toList())
.toList()
);
}


}
4 changes: 2 additions & 2 deletions backend/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ spring:
connectionTimeout: 30000
idleTimeout: 600000
maxLifetime: 1800000
keepaliveTime: 30000
keepaliveTime: 15000
poolName: SilvaOracleConnPool
minimumIdle: 1
maximumPoolSize: 3
leakDetectionThreshold: 60000
leakDetectionThreshold: 30000
datasource:
jdbcUrl: jdbc:postgresql://${POSTGRES_HOST:localhost}:5432/${POSTGRES_DB:nr-silva}
url: ${spring.datasource.jdbcUrl}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ CACHE 30;
-- Use the sequence in your table creation or insert statements
CREATE TABLE IF NOT EXISTS silva.user_recent_openings (
id BIGINT PRIMARY KEY DEFAULT nextval('silva.user_recent_openings_seq'),
opening_id VARCHAR(255) NOT NULL,
opening_id DECIMAL(10,0) NOT NULL,
user_id VARCHAR(255) NOT NULL,
last_viewed TIMESTAMP DEFAULT NOW()
);
Loading

0 comments on commit 337c414

Please sign in to comment.