Skip to content

Commit

Permalink
removed the unused recent-opening endpoint by ricardo
Browse files Browse the repository at this point in the history
  • Loading branch information
jazzgrewal committed Nov 5, 2024
1 parent f1c92fd commit bb589fe
Show file tree
Hide file tree
Showing 8 changed files with 4 additions and 205 deletions.
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
package ca.bc.gov.restapi.results.oracle.endpoint;

import ca.bc.gov.restapi.results.common.pagination.PaginatedResult;
import ca.bc.gov.restapi.results.common.pagination.PaginatedViaQuery;
import ca.bc.gov.restapi.results.common.pagination.PaginationParameters;
import ca.bc.gov.restapi.results.oracle.dto.RecentOpeningDto;
import ca.bc.gov.restapi.results.oracle.service.OpeningService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

Expand All @@ -22,23 +12,4 @@
public class OpeningEndpoint {

private final OpeningService openingService;

/**
* Fetches all recent openings for the home screen.
*
* @param paginationParameters {@link PaginationParameters} parameters
* @return List of {@link RecentOpeningDto} or empty list.
*/
@GetMapping(path = "/recent-openings", produces = MediaType.APPLICATION_JSON_VALUE)
@PaginatedViaQuery
@CrossOrigin(exposedHeaders = "x-opening-source")
public ResponseEntity<PaginatedResult<RecentOpeningDto>> getRecentOpenings(
@Valid PaginationParameters paginationParameters) {
PaginatedResult<RecentOpeningDto> userOpenings =
openingService.getRecentOpeningsCurrentUser(paginationParameters);

HttpHeaders headers = new HttpHeaders();
headers.set("x-opening-source", "user-based");
return ResponseEntity.ok().headers(headers).body(userOpenings);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,56 +50,7 @@ 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 @@ -64,7 +64,6 @@ void getRecentOpenings_fetchPaginated_shouldSucceed() throws Exception {

PaginationParameters params = new PaginationParameters(0, 5);

when(openingService.getRecentOpeningsCurrentUser(params)).thenReturn(paginatedResult);

mockMvc
.perform(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,53 +42,6 @@ class OpeningServiceTest extends AbstractTestContainerIntegrationTest {
@Autowired
private OpeningService openingService;

@Test
@DisplayName("Get a list of recent openings for logged user")
void getRecentOpenings_fetchPaginated_shouldSucceed() {
int pages = 3;
int currentPage = 0;

PaginationParameters pagination = new PaginationParameters(currentPage, pages);
PaginatedResult<RecentOpeningDto> paginatedResult =
openingService.getRecentOpeningsCurrentUser(pagination);

Assertions.assertNotNull(paginatedResult);
Assertions.assertEquals(currentPage, paginatedResult.getPageIndex());
Assertions.assertEquals(1, paginatedResult.getTotalPages());
Assertions.assertFalse(paginatedResult.getData().isEmpty());
Assertions.assertEquals(1, paginatedResult.getData().size());
}

@Test
@DisplayName("Get an empty list of recent openings for the home screen")
void getRecentOpenings_emptyPages_shouldSucceed() {

int currentPage = 0;
int pages = 1;
PaginationParameters pagination = new PaginationParameters(currentPage, pages);
PaginatedResult<RecentOpeningDto> paginatedResult =
openingService.getRecentOpeningsCurrentUser(pagination);

Assertions.assertNotNull(paginatedResult);
Assertions.assertEquals(currentPage, paginatedResult.getPageIndex());
Assertions.assertEquals(1, paginatedResult.getTotalPages());
Assertions.assertFalse(paginatedResult.getData().isEmpty());
}

@Test
@DisplayName("Get a list of recent openings without user")
void getRecentOpenings_fetchNoUserPaginated_shouldSucceed() {

PaginatedResult<RecentOpeningDto> paginatedResult =
openingService.getRecentOpenings(new PaginationParameters(1, 1));

Assertions.assertNotNull(paginatedResult);
Assertions.assertEquals(1, paginatedResult.getPageIndex());
Assertions.assertEquals(3, paginatedResult.getTotalPages());
Assertions.assertFalse(paginatedResult.getData().isEmpty());
Assertions.assertEquals(1, paginatedResult.getData().size());
}

@Test
@DisplayName("Opening search file id happy path should succeed")
void openingSearch_fileId_shouldSucceed() {
Expand Down
4 changes: 0 additions & 4 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@ const router = createBrowserRouter([
path: "/silviculture-search",
element: <SideLayout pageContent={<SilvicultureSearch />} />
},
{
path: "/opening/reports",
element: <SideLayout pageContent={<Reports />} />
},
{
path: "/help",
element: <SideLayout pageContent={<Help />} />
Expand Down
31 changes: 2 additions & 29 deletions frontend/src/components/OpeningsTab/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { Location } from '@carbon/icons-react';
import OpeningsMap from '../OpeningsMap';
import OpeningScreenDataTable from '../OpeningScreenDataTable/index';
import { columns } from '../Dashboard/Opening/RecentOpeningsDataTable/testData';
import { fetchRecentOpenings } from '../../services/OpeningService';
import SectionTitle from '../SectionTitle';
import TableSkeleton from '../TableSkeleton';
import { InlineNotification } from '@carbon/react';
Expand All @@ -24,7 +23,6 @@ interface Props {
}

const OpeningsTab: React.FC<Props> = ({ showSpatial, setShowSpatial }) => {
const [loading, setLoading] = useState<boolean>(true);
const [openingRows, setOpeningRows] = useState<RecentOpening[]>([]);
const [error, setError] = useState<string | null>(null);
const [loadId, setLoadId] = useState<number | null>(null);
Expand All @@ -34,32 +32,7 @@ const OpeningsTab: React.FC<Props> = ({ showSpatial, setShowSpatial }) => {
const { data, isFetching } = useUserRecentOpeningQuery(10);
const [headers, setHeaders] = useState<ITableHeader[]>(columns);

useEffect(() => {
const fetchData = async () => {
try {
const rows: RecentOpening[] = await fetchRecentOpenings();
setOpeningRows(rows);
setLoading(false);
setError(null);
} catch (error) {
console.error('Error fetching recent openings:', error);
setLoading(false);
setError('Failed to fetch recent openings');
}
};

const fetchAllowedPeople = async () => {
try {
const usersList: WmsLayersWhitelistUser[] = await getWmsLayersWhitelistUsers();
setWmsUsersWhitelist(usersList);
} catch (error) {
console.error('Error fetching recent openings:', error);
}
};

fetchData();
fetchAllowedPeople();
}, []);


useEffect(() => {}, [loadId, openingPolygonNotFound, wmsUsersWhitelist]);

Expand Down Expand Up @@ -143,7 +116,7 @@ const OpeningsTab: React.FC<Props> = ({ showSpatial, setShowSpatial }) => {
className = "inline-notification"
/>
) : null }
{loading ? (
{isFetching ? (
<TableSkeleton headers={headers} />
) : (
<RecentOpeningsDataTable
Expand Down
44 changes: 0 additions & 44 deletions frontend/src/services/OpeningService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,50 +27,6 @@ interface RecentOpeningApi {
updateTimestamp: string | null;
}

/**
* Fetch recent openings data from backend.
*
* @returns {Promise<RecentOpening[]>} Array of objects found
*/
export async function fetchRecentOpenings(): Promise<RecentOpening[]> {
const authToken = getAuthIdToken();
try {
const response = await axios.get(backendUrl.concat("/api/openings/recent-openings?page=0&perPage=100"), {
headers: {
Authorization: `Bearer ${authToken}`
}
});

if (response.status >= 200 && response.status < 300) {
const { data } = response;

if (data.data) {
// Extracting row information from the fetched data
const rows: RecentOpening[] = data.data.map((opening: RecentOpeningApi) => ({
id: opening.openingId.toString(),
openingId: opening.openingId.toString(),
forestFileId: opening.forestFileId ? opening.forestFileId : '-',
cuttingPermit: opening.cuttingPermit ? opening.cuttingPermit : '-',
timberMark: opening.timberMark ? opening.timberMark : '-',
cutBlock: opening.cutBlock ? opening.cutBlock : '-',
grossAreaHa: opening.grossAreaHa ? opening.grossAreaHa.toString() : '-',
status: opening.status && opening.status.description? opening.status.description : '-',
category: opening.category && opening.category.description? opening.category.description : '-',
disturbanceStart: opening.disturbanceStart ? opening.disturbanceStart : '-',
entryTimestamp: opening.entryTimestamp ? opening.entryTimestamp.split('T')[0] : '-',
updateTimestamp: opening.updateTimestamp ? opening.updateTimestamp.split('T')[0] : '-'
}));

return rows;
}
}
return [];
} catch (error) {
console.error('Error fetching recent openings:', error);
throw error;
}
}

/**
* Fetch openings per year data from backend.
*
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/services/search/openings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export const fetchUserRecentOpenings = async (limit: number): Promise<any> => {
const authToken = getAuthIdToken();

// Make the API request with the Authorization header
const response = await axios.get(`${backendUrl}/api/user/recent-openings`, {
const response = await axios.get(`${backendUrl}/api/openings/recent`, {
headers: {
Authorization: `Bearer ${authToken}`
}
Expand Down

0 comments on commit bb589fe

Please sign in to comment.