Compare commits

..

2 Commits

Author SHA1 Message Date
db7a5444b3 adding pagination to logbook table 2026-03-16 07:28:01 -05:00
6964531e12 Update logbook table pagesize (#110)
* updating default logbook table page size

* updating default logbook table page size
2026-03-08 18:05:38 -05:00
8 changed files with 206 additions and 60 deletions

View File

@@ -13,7 +13,7 @@ describe('LogController', () => {
create: jest.fn(), create: jest.fn(),
delete: jest.fn(), delete: jest.fn(),
find: jest.fn(), find: jest.fn(),
findAll: jest.fn(), findLogsWithCount: jest.fn(),
update: jest.fn() update: jest.fn()
} }
@@ -69,32 +69,32 @@ describe('LogController', () => {
} }
}) })
it('findAll => should find all logs', async () => { it('findLogsWithCount => should find all logs', async () => {
const id: string = '95834f84-0a02-44d3-884e-a20237adeca0'; const id: string = '95834f84-0a02-44d3-884e-a20237adeca0';
const log = { const log = {
} as LogEntity; } as LogEntity;
const logs = [log] const logs = [log]
jest.spyOn(mockLogService, 'findAll').mockReturnValue(logs); jest.spyOn(mockLogService, 'findLogsWithCount').mockReturnValue(logs);
const result = await controller.findAll(); const result = await controller.findLogsWithCount();
expect(result).toEqual(logs); expect(result).toEqual(logs);
expect(mockLogService.findAll).toHaveBeenCalled(); expect(mockLogService.findLogsWithCount).toHaveBeenCalled();
}) })
it('findAll => should fail to find all logs', async () => { it('findLogsWithCount => should fail to find logs with count', async () => {
jest.spyOn(mockLogService, 'findAll').mockRejectedValue(new Error('Logs not found')) jest.spyOn(mockLogService, 'findLogsWithCount').mockRejectedValue(new Error('Logs not found'))
try { try {
await controller.findAll(); await controller.findLogsWithCount();
fail('findAll did not throw error'); fail('findLogsWithCount did not throw error');
} catch (error) { } catch (error) {
expect(error).toBeInstanceOf(Error); expect(error).toBeInstanceOf(Error);
expect(mockLogService.findAll).toHaveBeenCalled(); expect(mockLogService.findLogsWithCount).toHaveBeenCalled();
expect(mockLogService.findAll).rejects.toThrow('Logs not found') expect(mockLogService.findLogsWithCount).rejects.toThrow('Logs not found')
} }
}) })

View File

@@ -7,6 +7,7 @@ import {
Param, Param,
Post, Post,
Put, Put,
Query,
UseGuards, UseGuards,
UseInterceptors UseInterceptors
} from '@nestjs/common'; } from '@nestjs/common';
@@ -47,13 +48,13 @@ export class LogController {
@Get() @Get()
@Public() @Public()
async findAll(): Promise<LogEntity[]> { async findLogsWithCount(@Query('skip') skip?, @Query('take') take?: number,): Promise<{ entities: LogEntity[], total: number, hasNextPage: boolean }> {
try { try {
return await this.logService.findAll(); return await this.logService.findLogsWithCount(skip, take)
} catch (error) { } catch (error) {
const customError = error as CustomError; const customError = error as CustomError;
throw new HttpException(customError.message, customError.statusCode); throw new HttpException(customError.message, customError.statusCode)
} }
} }

View File

@@ -15,10 +15,10 @@ export class LogInterceptor implements NestInterceptor {
]); ]);
return handler.handle().pipe( return handler.handle().pipe(
map((data: LogEntity[]) => { map((data: { entities: LogEntity[], total: number, hasNextPage: boolean }) => {
const req = context.switchToHttp().getRequest(); const req = context.switchToHttp().getRequest();
const limitData = (data) => { const limitData = (entities: LogEntity[]) => {
return data.map((log: LogEntity) => { return entities.map((log: LogEntity) => {
return { return {
id: log.id, id: log.id,
pilot: { pilot: {
@@ -41,17 +41,25 @@ export class LogInterceptor implements NestInterceptor {
const rolesKeyName = Object.keys(jwtPayload).find((key) => key.includes('roles')); const rolesKeyName = Object.keys(jwtPayload).find((key) => key.includes('roles'));
if (jwtPayload[rolesKeyName].includes('Flying.Read')) { if (jwtPayload[rolesKeyName].includes('Flying.Read')) {
const logs = limitData(data); const logs = limitData(data.entities);
return logs; return {
entities: logs,
total: data.total,
hasNextPage: data.hasNextPage
};
} else { } else {
return data; return data;
} }
} else if (!req.headers.authorization && isPublic) { } else if (!req.headers.authorization && isPublic) {
const publicData = limitData(data) const publicData = limitData(data.entities)
const logs = publicData.slice(0, 5) const logs = publicData.slice(0, 5)
return logs; return {
entities: logs,
total: data.total,
hasNextPage: data.hasNextPage
};
} }
}) })
); );

View File

@@ -17,7 +17,7 @@ describe('LogService', () => {
const mockLogRepository = { const mockLogRepository = {
delete: jest.fn(), delete: jest.fn(),
find: jest.fn(), findAndCount: jest.fn(),
findOne: jest.fn(), findOne: jest.fn(),
findOneBy: jest.fn(), findOneBy: jest.fn(),
save: jest.fn(), save: jest.fn(),
@@ -181,7 +181,7 @@ describe('LogService', () => {
}) })
}) })
it('findAll => should find all log entries', async () => { it('findLogsWithCount => should find log entries with count', async () => {
const log = { const log = {
id: 'd685f1ca-28e0-40b9-8713-74467db12965', id: 'd685f1ca-28e0-40b9-8713-74467db12965',
pilotId: '7c4bae6b-9ec4-469e-8e16-fcbf0b940936', pilotId: '7c4bae6b-9ec4-469e-8e16-fcbf0b940936',
@@ -209,14 +209,18 @@ describe('LogService', () => {
notes: 'This is a test', notes: 'This is a test',
tracks: [] tracks: []
} as LogEntity; } as LogEntity;
const logs = [log] const logs = [log];
const count = 1
const morePages = false
jest.spyOn(mockLogRepository, 'findAndCount').mockReturnValue([logs, count, morePages]);
jest.spyOn(mockLogRepository, 'find').mockReturnValue(logs); const {entities, total, hasNextPage} = await service.findLogsWithCount();
const result = await service.findAll(); expect(entities).toEqual(logs);
expect(count).toEqual(total);
expect(result).toEqual(logs); expect(hasNextPage).toEqual(morePages);
expect(mockLogRepository.find).toHaveBeenCalled(); expect(mockLogRepository.findAndCount).toHaveBeenCalled();
}) })
it('update => should update a log entry', async () => { it('update => should update a log entry', async () => {

View File

@@ -25,10 +25,18 @@ export class LogService {
return logEntity; return logEntity;
} }
async findAll(): Promise<LogEntity[]> { async findLogsWithCount(skip?: number, take?: number): Promise<{entities: LogEntity[], total: number, hasNextPage: boolean}> {
return await this.logRepository.find({ const [entities, total] = await this.logRepository.findAndCount({
take,
skip,
relations: ['pilot', 'tracks'] relations: ['pilot', 'tracks']
}); })
return {
entities,
total,
hasNextPage: skip + take < total
}
} }
async create(logDto: LogDto): Promise<LogDto> { async create(logDto: LogDto): Promise<LogDto> {

View File

@@ -12,16 +12,16 @@ import { UserRole } from '../../enums/userRole';
import { useBreakpoints } from '../../hooks/useBreakpoints/UseBreakpoints'; import { useBreakpoints } from '../../hooks/useBreakpoints/UseBreakpoints';
import { ScreenSize } from '../../enums/screenSize'; import { ScreenSize } from '../../enums/screenSize';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faAdd, faEllipsisVertical, faPen, faEye, faTrash, faMapLocationDot } from '@fortawesome/free-solid-svg-icons' import { faAdd, faEllipsisVertical, faPen, faEye, faTrash, faAngleLeft, faAngleRight, faAnglesLeft, faAnglesRight } from '@fortawesome/free-solid-svg-icons'
import { CellContext, ColumnDef, flexRender, getCoreRowModel, getPaginationRowModel, HeaderContext, useReactTable } from '@tanstack/react-table'; import { CellContext, ColumnDef, flexRender, getCoreRowModel, HeaderContext, PaginationState, useReactTable } from '@tanstack/react-table';
import { useLogbookContext } from '../../hooks/logbookContext/UseLogbookContext'; import { useLogbookContext } from '../../hooks/logbookContext/UseLogbookContext';
import LogbookDrawer from '../logbookDrawer/LogbookDrawer'; import LogbookDrawer from '../logbookDrawer/LogbookDrawer';
import Alert from '../alert/Alert'; import Alert from '../alert/Alert';
const Logbook: React.FC<unknown> = () => { const Logbook: React.FC<unknown> = () => {
const [state, dispatch] = useReducer(reducer, initialState); const [state, dispatch] = useReducer(reducer, initialState);
const [columnVisibility, setColumnVisibility] = useState({}) const [columnVisibility, setColumnVisibility] = useState({});
const logbookContext = useLogbookContext() const logbookContext = useLogbookContext();
const { isUserLoggedIn } = useOidc(); const { isUserLoggedIn } = useOidc();
const { userRole } = useUserRole(); const { userRole } = useUserRole();
const { screenSize } = useBreakpoints(); const { screenSize } = useBreakpoints();
@@ -338,31 +338,51 @@ const Logbook: React.FC<unknown> = () => {
actions actions
]; ];
const onPaginationChange = (updater: any) => {
const newPaginationState: PaginationState = typeof updater === 'function' ? updater(state.pagination) : updater;
dispatch({ type: 'SET_PAGINATION', payload: newPaginationState })
}
const table = useReactTable({ const table = useReactTable({
data: state.entries, data: state.entries,
columns: columns, columns: columns,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(), manualPagination: true,
initialState: {
pagination: {
pageIndex: 0,
pageSize: 100
}
},
onColumnVisibilityChange: setColumnVisibility, onColumnVisibilityChange: setColumnVisibility,
onPaginationChange: onPaginationChange,
rowCount: state.totalEntries,
state: { state: {
columnVisibility: columnVisibility, columnVisibility: columnVisibility,
pagination: state.pagination
} }
}); });
const getLogbookEntries = async () => { const {
firstPage,
getCanNextPage,
getCanPreviousPage,
getPageCount,
getState,
lastPage,
nextPage,
previousPage,
setPageIndex
} = table;
const getLogbookEntries = async (pageIndex?: number, pageSize?: number) => {
try { try {
dispatch({ type: 'SET_IS_LOADING', payload: true }); dispatch({ type: 'SET_IS_LOADING', payload: true });
const response: AxiosResponse = await httpClient.get(`api/logs`); const response: AxiosResponse = await httpClient.get(`api/logs`, {
params: {
skip: pageIndex,
take: pageSize
}
});
if (response.data.length > 0) { if (response.data.entities.length > 0) {
const entries: LogbookEntry[] = response.data; const entries: LogbookEntry[] = response.data.entities;
const entryColumns: string[] = Object.keys(entries[0]); const entryColumns: string[] = Object.keys(entries[0]);
const columnVisibility: {[key: string]: boolean} = {} const columnVisibility: {[key: string]: boolean} = {}
@@ -381,7 +401,7 @@ const Logbook: React.FC<unknown> = () => {
entries.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()); entries.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
setColumnVisibility(columnVisibility) setColumnVisibility(columnVisibility)
dispatch({ type: 'SET_ENTRIES', payload: entries }); dispatch({ type: 'SET_ENTRIES', payload: { entries: entries, totalEntries: response.data.total }});
if (!isUserLoggedIn && response.data.length >= 5) { if (!isUserLoggedIn && response.data.length >= 5) {
dispatch({ type: 'SET_ALERT', payload: { severity: 'info', message: 'A limited number of log entries displayed. Sign in to view all log entries.'}}) dispatch({ type: 'SET_ALERT', payload: { severity: 'info', message: 'A limited number of log entries displayed. Sign in to view all log entries.'}})
@@ -448,7 +468,7 @@ const Logbook: React.FC<unknown> = () => {
payload: false payload: false
}); });
logbookContext.dispatch({ type: 'SET_SELECTED_LOG_ID', payload: '' }) logbookContext.dispatch({ type: 'SET_SELECTED_LOG_ID', payload: '' })
await getLogbookEntries(); await getLogbookEntries(state.pagination?.pageIndex, state.pagination?.pageSize);
} catch (error) { } catch (error) {
const axiosError = error as AxiosError; const axiosError = error as AxiosError;
@@ -468,11 +488,35 @@ const Logbook: React.FC<unknown> = () => {
}); });
}; };
const onRowsPerPageChanged = (event: any) => {
console.log(event.target.value)
const newPaginationState: PaginationState = {
pageIndex: 0,
pageSize: event.target.value !== 'All' ? Number(event.target.value) : state.totalEntries
};
console.log(newPaginationState)
dispatch({ type: 'SET_PAGINATION', payload: newPaginationState })
}
useEffect(() => { useEffect(() => {
if (!logbookContext.state.isDrawerOpen) { if (!logbookContext.state.isDrawerOpen) {
getLogbookEntries(); getLogbookEntries(state.pagination.pageIndex, state.pagination.pageSize);
} }
}, [logbookContext.state.isDrawerOpen]); }, [logbookContext.state.isDrawerOpen, state.pagination.pageIndex, state.pagination.pageSize]);
useEffect(() => {
const pages: number[] = [];
if (state.pagination?.pageSize) {
const totalPages = getPageCount();
for(let i = 0; i < totalPages; i++) {
pages.push(i + 1)
}
}
dispatch({ type: 'SET_PAGES', payload: pages })
}, [state.totalEntries, state.pagination?.pageSize])
return ( return (
<> <>
@@ -504,8 +548,24 @@ const Logbook: React.FC<unknown> = () => {
</div> </div>
)} )}
{!state.isLoading && state.entries.length > 0 && screenSize !== ScreenSize.SM && ( {!state.isLoading && state.entries.length > 0 && screenSize !== ScreenSize.SM && (
<div className='col-span-12 p-5 bg-base-100 border border-base-100 rounded-lg'> <div className='col-span-12 pr-5 pb-5 pl-5 bg-base-100 border border-base-100 rounded-lg '>
<div className='overflow-x-auto'> <div className='overflow-x-auto mb-5'>
<div className='col-span-12 justify-self-end self-center mt-1 mr-1 mb-2'>
<label className='select select-sm select-ghost'>
<span className='label'>Rows per page</span>
<select
defaultValue={1}
onChange={onRowsPerPageChanged}
value={state.pagination?.pageSize}
>
<option value={10}>10</option>
<option value={25}>25</option>
<option value={3}>50</option>
<option value={state.totalEntries}>All</option>
</select>
</label>
</div>
<table className='table min-w-full h-auto table-auto w-full'> <table className='table min-w-full h-auto table-auto w-full'>
<thead className='bg-base-200'> <thead className='bg-base-200'>
{table.getHeaderGroups().map((headerGroup, headerGroupIndex) => ( {table.getHeaderGroups().map((headerGroup, headerGroupIndex) => (
@@ -591,6 +651,48 @@ const Logbook: React.FC<unknown> = () => {
</thead> </thead>
</table> </table>
</div> </div>
{state.pagination.pageSize !== state.totalEntries &&
<div className='col-span-12 justify-self-center self-center'>
<div className='join'>
<button
className='join-item btn btn-sm'
onClick={firstPage}
>
<FontAwesomeIcon icon={faAnglesLeft} />
</button>
<button
className='join-item btn btn-sm'
onClick={previousPage}
disabled={!getCanPreviousPage()}
>
<FontAwesomeIcon icon={faAngleLeft} />
</button>
{state.pages.map((page, index) => {
return (
<button
className={`join-item btn btn-sm ${getState().pagination.pageIndex === index ? 'btn-active' : ''}`}
onClick={() => setPageIndex(index)}
>
{page}
</button>
)
})}
<button
className='join-item btn btn-sm'
onClick={() => nextPage()}
disabled={!getCanNextPage()}
>
<FontAwesomeIcon icon={faAngleRight} />
</button>
<button
className='join-item btn btn-sm'
onClick={lastPage}
>
<FontAwesomeIcon icon={faAnglesRight} />
</button>
</div>
</div>
}
</div> </div>
)} )}
{state.entries.length > 0 && screenSize === ScreenSize.SM && {state.entries.length > 0 && screenSize === ScreenSize.SM &&

View File

@@ -1,4 +1,4 @@
import { ColumnDef } from '@tanstack/react-table'; import { ColumnDef, PaginationState } from '@tanstack/react-table';
import { FormMode } from '../../enums/formMode'; import { FormMode } from '../../enums/formMode';
import { Alert } from '../../interfaces/Alert.interface'; import { Alert } from '../../interfaces/Alert.interface';
import { LogbookEntry } from './LogbookEntry.interface'; import { LogbookEntry } from './LogbookEntry.interface';
@@ -10,4 +10,7 @@ export interface LogbookState {
isConfirmDialogLoading: boolean; isConfirmDialogLoading: boolean;
isConfirmDialogOpen: boolean; isConfirmDialogOpen: boolean;
isLoading: boolean; isLoading: boolean;
pages: number[];
pagination: PaginationState;
totalEntries: number;
} }

View File

@@ -1,4 +1,4 @@
import { ColumnDef } from '@tanstack/react-table'; import { ColumnDef, PaginationState } from '@tanstack/react-table';
import { FormMode } from '../../enums/formMode'; import { FormMode } from '../../enums/formMode';
import { Alert } from '../../interfaces/Alert.interface'; import { Alert } from '../../interfaces/Alert.interface';
import { LogbookEntry } from './LogbookEntry.interface'; import { LogbookEntry } from './LogbookEntry.interface';
@@ -7,11 +7,12 @@ import { LogbookState } from './LogbookState.interface';
type Action = type Action =
| { type: 'SET_COLUMNS'; payload: ColumnDef<LogbookEntry>[] } | { type: 'SET_COLUMNS'; payload: ColumnDef<LogbookEntry>[] }
| { type: 'SET_IS_CONFIRMATION_DIALOG_OPEN'; payload: boolean } | { type: 'SET_IS_CONFIRMATION_DIALOG_OPEN'; payload: boolean }
| { type: 'SET_ENTRIES'; payload: LogbookEntry[] } | { type: 'SET_ENTRIES'; payload: { entries: LogbookEntry[], totalEntries: number } }
| { type: 'SET_ALERT'; payload: Alert | undefined } | { type: 'SET_ALERT'; payload: Alert | undefined }
| { type: 'SET_IS_CONFIRMATION_DIALOG_LOADING'; payload: boolean } | { type: 'SET_IS_CONFIRMATION_DIALOG_LOADING'; payload: boolean }
| { type: 'SET_IS_LOADING'; payload: boolean }; | { type: 'SET_IS_LOADING'; payload: boolean }
| { type: 'SET_PAGES'; payload: number[] }
| { type: 'SET_PAGINATION'; payload: PaginationState };
export const initialState: LogbookState = { export const initialState: LogbookState = {
alert: undefined, alert: undefined,
@@ -19,7 +20,13 @@ export const initialState: LogbookState = {
entries: [], entries: [],
isConfirmDialogLoading: false, isConfirmDialogLoading: false,
isConfirmDialogOpen: false, isConfirmDialogOpen: false,
isLoading: false isLoading: false,
pages: [],
pagination: {
pageIndex: 0,
pageSize: 10
},
totalEntries: 0
}; };
export const reducer = ( export const reducer = (
@@ -42,7 +49,8 @@ export const reducer = (
case 'SET_ENTRIES': { case 'SET_ENTRIES': {
return { return {
...state, ...state,
entries: action.payload entries: action.payload.entries,
totalEntries: action.payload.totalEntries
}; };
} }
case 'SET_ALERT': { case 'SET_ALERT': {
@@ -63,6 +71,18 @@ export const reducer = (
isLoading: action.payload isLoading: action.payload
}; };
} }
case 'SET_PAGES': {
return {
...state,
pages: action.payload
}
}
case 'SET_PAGINATION': {
return {
...state,
pagination: action.payload
}
}
default: { default: {
return state; return state;
} }