Compare commits

..

1 Commits

Author SHA1 Message Date
0fa29cf4fd switching to auth0 2025-12-01 22:04:41 -06:00
45 changed files with 4318 additions and 1068 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@@ -1,4 +1,4 @@
FROM node:22 FROM --platform=linux/amd64 node:22-slim
WORKDIR app WORKDIR app
COPY ./api/dist ./api/dist COPY ./api/dist ./api/dist
@@ -9,10 +9,10 @@ WORKDIR api
RUN npm ci RUN npm ci
WORKDIR / WORKDIR /
COPY ./api/entrypoint.sh ./app/entrypoint.sh COPY ./api/entrypoint.sh ./entrypoint.sh
RUN chmod +x ./app/entrypoint.sh RUN chmod +x entrypoint.sh
EXPOSE 3000 EXPOSE 3000
CMD ["./app/entrypoint.sh"] ENTRYPOINT ["/entrypoint.sh"]
# ENTRYPOINT ["tail", "-f", "/dev/null"] # ENTRYPOINT ["tail", "-f", "/dev/null"]

View File

@@ -1,4 +1,3 @@
#!/bin/bash #!/bin/bash
cd ./app npx typeorm migration:run -d ./app/api/dist/database/data-source.js
npx typeorm migration:run -d ./api/dist/database/data-source.js node ./app/api/dist/main.js
node ./api/dist/main.js

View File

@@ -35,7 +35,7 @@
"@nestjs/serve-static": "^5.0.3", "@nestjs/serve-static": "^5.0.3",
"@nestjs/typeorm": "^11.0.0", "@nestjs/typeorm": "^11.0.0",
"@noahspan/azure-database": "^3.1.2", "@noahspan/azure-database": "^3.1.2",
"@noahspan/noahspan-modules": "^1.2.11", "@noahspan/noahspan-modules": "^1.2.9",
"@schematics/angular": "^17.3.7", "@schematics/angular": "^17.3.7",
"@types/multer": "^1.4.12", "@types/multer": "^1.4.12",
"better-sqlite3": "^12.2.0", "better-sqlite3": "^12.2.0",

View File

@@ -32,18 +32,17 @@ import { join } from 'path';
}), }),
HealthModule, HealthModule,
LogModule, LogModule,
MsGraphModule.registerAsync({ // MsGraphModule.registerAsync({
inject: [ConfigService], // inject: [ConfigService],
imports: [ConfigModule], // imports: [ConfigModule],
useFactory: async (configService: ConfigService) => { // useFactory: async (configService: ConfigService) => {
return { // return {
authority: configService.get<string>('authority'), // clientId: configService.get<string>('clientId'),
clientId: configService.get<string>('clientId'), // clientSecret: configService.get<string>('clientSecret'),
clientSecret: configService.get<string>('clientSecret'), // tenantId: configService.get<string>('tenantId')
tenantId: configService.get<string>('tenantId') // }
} // }
} // }),
}),
PilotModule, PilotModule,
ServeStaticModule.forRoot({ ServeStaticModule.forRoot({
rootPath: join(__dirname, '../..', 'client', 'dist') rootPath: join(__dirname, '../..', 'client', 'dist')

View File

@@ -1,7 +1,6 @@
export default () => ({ export default () => ({
azureStorageConnectionString: process.env.AZURE_STORAGE_CONNECTION_STRING, azureStorageConnectionString: process.env.AZURE_STORAGE_CONNECTION_STRING,
audience: process.env.AUDIENCE, audience: process.env.AUDIENCE,
authority: process.env.AUTHORITY,
clientId: process.env.CLIENT_ID, clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET, clientSecret: process.env.CLIENT_SECRET,
issuer: process.env.ISSUER_URL, issuer: process.env.ISSUER_URL,

View File

@@ -65,7 +65,7 @@ export class LogController {
return await this.logService.create(logDto); return await this.logService.create(logDto);
} catch (error) { } catch (error) {
const customError = error as CustomError; const customError = error as CustomError;
console.log(error)
throw new HttpException(customError.message, customError.statusCode); throw new HttpException(customError.message, customError.statusCode);
} }
} }

View File

@@ -10,15 +10,15 @@ async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
app.enableCors({ app.enableCors({
origin: 'http://localhost:8080', origin: 'http://localhost:8080', // Allow requests from your frontend's origin
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true, credentials: true, // If you need to send cookies or authorization headers
}); });
app.setGlobalPrefix('api'); app.setGlobalPrefix('api');
app.useGlobalFilters(new HttpExceptionFilter()); app.useGlobalFilters(new HttpExceptionFilter());
app.use( app.use(
session({ session({
secret: process.env.SESSION_SECRET, secret: 'blah',
resave: false, resave: false,
saveUninitialized: false saveUninitialized: false
}) })

View File

@@ -29,7 +29,6 @@ export class PilotInterceptor implements NestInterceptor {
if (req.headers.authorization) { if (req.headers.authorization) {
const authHeader = req.headers.authorization; const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(' ')[1]; const token = authHeader && authHeader.split(' ')[1];
const jwtPayload = jwtDecode(token); const jwtPayload = jwtDecode(token);
const rolesKeyName = Object.keys(jwtPayload).find((key) => key.includes('roles')); const rolesKeyName = Object.keys(jwtPayload).find((key) => key.includes('roles'));

View File

@@ -14,12 +14,14 @@
"@fortawesome/fontawesome-svg-core": "^7.1.0", "@fortawesome/fontawesome-svg-core": "^7.1.0",
"@fortawesome/free-solid-svg-icons": "^7.1.0", "@fortawesome/free-solid-svg-icons": "^7.1.0",
"@fortawesome/react-fontawesome": "^3.1.0", "@fortawesome/react-fontawesome": "^3.1.0",
"@heroui/react": "^2.8.5",
"@noahspan/noahspan-components": "^2.0.0-alpha-14", "@noahspan/noahspan-components": "^2.0.0-alpha-14",
"@tailwindcss/typography": "^0.5.19", "@tailwindcss/typography": "^0.5.19",
"@tailwindcss/vite": "^4.1.13", "@tailwindcss/vite": "^4.1.13",
"@tanstack/react-table": "^8.21.3", "@tanstack/react-table": "^8.21.3",
"axios": "^1.7.2", "axios": "^1.7.2",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"framer-motion": "^12.23.24",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
"oidc-spa": "^7.2.4", "oidc-spa": "^7.2.4",
"react": "^19.1.1", "react": "^19.1.1",

View File

@@ -1,22 +1,23 @@
import { Route, Routes } from 'react-router-dom'; import { Navigate, Route, Routes } from 'react-router-dom';
import Flights from './components/flights/Flights'; import Flights from './components/flights/Flights';
import Logbook from './components/logbook/Logbook'; import Logbook from './components/logbook/Logbook';
import Pilots from './components/pilots/Pilots'; import Pilots from './components/pilots/Pilots';
import SiteNav from './components/siteNav/SiteNav'; import SiteNav from './components/siteNav/SiteNav';
import { useNavigate } from 'react-router-dom'; import { HeroUIProvider } from '@heroui/react';
import { useHref, useNavigate } from 'react-router-dom';
const App = () => { const App = () => {
const navigate = useNavigate(); const navigate = useNavigate();
return ( return (
<div className='bg-[#f5f5f5]' data-theme="lofi"> <HeroUIProvider navigate={navigate} useHref={useHref}>
<SiteNav /> <SiteNav />
<Routes> <Routes>
<Route path='/' element={<Flights />} /> <Route path='/' element={<Flights />} />
<Route path="/logbook" element={<Logbook />} /> <Route path="/logbook" element={<Logbook />} />
<Route path="/pilots" element={<Pilots />} /> <Route path="/pilots" element={<Pilots />} />
</Routes> </Routes>
</div> </HeroUIProvider>
); );
}; };

View File

@@ -4,8 +4,10 @@ export const { OidcProvider, useOidc, getOidc } = createReactOidc(async () => ({
issuerUri: import.meta.env.VITE_ISSUER_URI, issuerUri: import.meta.env.VITE_ISSUER_URI,
clientId: import.meta.env.VITE_CLIENT_ID, clientId: import.meta.env.VITE_CLIENT_ID,
homeUrl: import.meta.env.VITE_BASE_URL, homeUrl: import.meta.env.VITE_BASE_URL,
scopes: ['email', 'openid', 'profile', `api://${import.meta.env.VITE_CLIENT_ID}/user_impersonation`],
autoLogin: false, autoLogin: false,
postLoginRedirectUrl: '/', postLoginRedirectUrl: '/',
noIframe: true, noIframe: true,
extraQueryParams: {
audience: "api://flying-test-api"
}
})); }));

View File

@@ -1,44 +0,0 @@
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AlertProps } from "./AlertProps.interface";
import { faCircleCheck, faCircleInfo, faCircleXmark, faTriangleExclamation, faXmark } from "@fortawesome/free-solid-svg-icons";
const Alert = ({
children,
className,
closeIcon,
severity,
onClose,
...rest
}: AlertProps) => {
const severityVariants = {
info: 'alert-info',
error: 'alert-error',
success: 'alert-success',
warning: 'alert-warning'
};
return (
<>
<div
role='alert'
className={`alert ${severity ? severityVariants[severity] : ''} ${className ? className : ''}`}
{...rest}
>
<span>
{severity === 'info' && <FontAwesomeIcon icon={faCircleInfo} />}
{severity === 'error' && <FontAwesomeIcon icon={faCircleXmark} />}
{severity === 'success' && (
<FontAwesomeIcon icon={faCircleCheck} />
)}
{severity === 'warning' && (
<FontAwesomeIcon icon={faTriangleExclamation} />
)}
</span>
<span>{children}</span>
{closeIcon && <button className='btn' onClick={onClose}>{<FontAwesomeIcon icon={faXmark} />}</button>}
</div>
</>
);
};
export default Alert;

View File

@@ -1,7 +0,0 @@
export interface AlertProps {
children?: React.ReactNode;
className?: string;
closeIcon?: React.ReactNode;
onClose?: () => void;
severity: 'info' | 'error' | 'success' | 'warning';
}

View File

@@ -7,6 +7,7 @@
// IconName, // IconName,
// Loading // Loading
// } from '@noahspan/noahspan-components'; // } from '@noahspan/noahspan-components';
import { Button, Modal, ModalBody, ModalContent, ModalHeader, ModalFooter, Spinner } from '@heroui/react'
import { DialogConfirmationProps } from './ConfirmationDialogProps.interface'; import { DialogConfirmationProps } from './ConfirmationDialogProps.interface';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCircleCheck, faXmark } from '@fortawesome/free-solid-svg-icons'; import { faCircleCheck, faXmark } from '@fortawesome/free-solid-svg-icons';
@@ -20,25 +21,31 @@ const ConfirmationDialog = ({
title title
}: DialogConfirmationProps) => { }: DialogConfirmationProps) => {
return ( return (
<> <Modal
<input type='checkbox' id='dialog' className='modal-toggle' onChange={() => {}} checked={isOpen} /> isDismissable={false}
<div className='modal' role='dialog'> isKeyboardDismissDisabled={true}
<div className='modal-box'> isOpen={isOpen}
<h3 className="text-lg font-bold">{title}</h3> >
<p className="py-4">{contentText}</p> <ModalContent>
<div className='modal-action'> <ModalHeader>{title}</ModalHeader>
<button className='btn' onClick={onCancel}> <ModalBody>
<FontAwesomeIcon icon={faXmark} /> {!isLoading && <div>{contentText}</div>}
No {isLoading && <Spinner size='lg' />}
</button> </ModalBody>
<button className='btn btn-primary' onClick={onConfirm}> <ModalFooter>
<FontAwesomeIcon icon={faCircleCheck} /> <Button onPress={onCancel} startContent={<FontAwesomeIcon icon={faXmark} />}>
Yes No
</button> </Button>
</div> <Button
</div> color='primary'
</div> onPress={onConfirm}
</> startContent={<FontAwesomeIcon icon={faCircleCheck} />}
>
Yes
</Button>
</ModalFooter>
</ModalContent>
</Modal>
); );
}; };

View File

@@ -1,9 +1,11 @@
import { Icon, IconName, Skeleton } from "@noahspan/noahspan-components";
import { Card } from '@heroui/react';
import LogbookCard from "../logbookCard/LogbookCard"; import LogbookCard from "../logbookCard/LogbookCard";
import { useEffect, useReducer } from "react"; import { useEffect, useReducer } from "react";
import { useLogs } from "../../hooks/logs/UseLogs"; import { useLogs } from "../../hooks/logs/UseLogs";
import { LogbookEntry } from "../logbook/LogbookEntry.interface"; import { LogbookEntry } from "../logbook/LogbookEntry.interface";
import { initialState, reducer } from "./reducer"; import { initialState, reducer } from "./reducer";
import Alert from "../alert/Alert"; import { Alert } from '@heroui/react'
const Flights = () => { const Flights = () => {
const [state, dispatch] = useReducer(reducer, initialState); const [state, dispatch] = useReducer(reducer, initialState);
@@ -21,7 +23,7 @@ const Flights = () => {
dispatch({ type: 'SET_FLIGHTS', payload: flights}) dispatch({ type: 'SET_FLIGHTS', payload: flights})
dispatch({ type: 'SET_ALERT', payload: undefined }) dispatch({ type: 'SET_ALERT', payload: undefined })
} else { } else {
dispatch({ type: 'SET_ALERT', payload: { severity: 'info', message: 'No flights found' }}) dispatch({ type: 'SET_ALERT', payload: { severity: 'default', message: 'No flights found' }})
} }
}, [logs]) }, [logs])
@@ -33,14 +35,12 @@ const Flights = () => {
{!logsLoading && state.alert && ( {!logsLoading && state.alert && (
<div> <div>
<Alert <Alert
className='mb-5'
onClose={() => onClose={() =>
dispatch({ type: 'SET_ALERT', payload: undefined }) dispatch({ type: 'SET_ALERT', payload: undefined })
} }
severity={state.alert.severity} color={state.alert.severity}
> title={state.alert.message}
{state.alert.message} />
</Alert>
</div> </div>
)} )}
{!logsLoading && {!logsLoading &&
@@ -48,7 +48,7 @@ const Flights = () => {
<LogbookCard logs={state.flights} mode='flights' /> <LogbookCard logs={state.flights} mode='flights' />
</div> </div>
} }
{/* {logsLoading && [...Array(6)].map((_element, index) => { {logsLoading && [...Array(6)].map((_element, index) => {
return ( return (
<div className='mb-5'> <div className='mb-5'>
<Card <Card
@@ -70,7 +70,7 @@ const Flights = () => {
</Card> </Card>
</div> </div>
) )
})} */} })}
</div> </div>
) )
} }

View File

@@ -1,5 +1,6 @@
import { useEffect, useReducer } from 'react'; import React, { useEffect, useReducer } from 'react';
import { useForm, Controller, useFormContext } from 'react-hook-form'; import { Alert, Button, DatePicker, Drawer, DrawerBody, DrawerContent, DrawerFooter, DrawerHeader, Input, NumberInput, Select, Selection, SelectItem, SharedSelection, Textarea } from '@heroui/react'
import { useForm, Controller, FormProvider, useFormContext } from 'react-hook-form';
import { LogFormProps } from './LogFormProps.interface'; import { LogFormProps } from './LogFormProps.interface';
import { initialState, reducer } from './reducer'; import { initialState, reducer } from './reducer';
import { AxiosError, AxiosResponse } from 'axios'; import { AxiosError, AxiosResponse } from 'axios';
@@ -9,6 +10,7 @@ import { useOidc } from '../../auth/oidcConfig';
import httpClient from '../../httpClient/httpClient'; import httpClient from '../../httpClient/httpClient';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSave, faXmark } from '@fortawesome/free-solid-svg-icons' import { faSave, faXmark } from '@fortawesome/free-solid-svg-icons'
import { parseAbsolute, parseDate, getLocalTimeZone, CalendarDate, ZonedDateTime } from '@internationalized/date';
import { useLogbookContext } from '../../hooks/logbookContext/UseLogbookContext'; import { useLogbookContext } from '../../hooks/logbookContext/UseLogbookContext';
const LogForm = () => { const LogForm = () => {
@@ -38,7 +40,7 @@ const LogForm = () => {
} catch (error) { } catch (error) {
const axiosError = error as AxiosError; const axiosError = error as AxiosError;
dispatch({ type: 'SET_ALERT', payload: { severity: 'error', message: axiosError.message }}); dispatch({ type: 'SET_ALERT', payload: { severity: 'danger', message: axiosError.message }});
} finally { } finally {
dispatch({ type: 'SET_IS_LOADING', payload: false }); dispatch({ type: 'SET_IS_LOADING', payload: false });
} }
@@ -57,7 +59,7 @@ const LogForm = () => {
label: pilot.name, label: pilot.name,
}; };
}); });
console.log(newPilotsOptions)
dispatch({ type: 'SET_PILOT_OPTIONS', payload: newPilotsOptions }); dispatch({ type: 'SET_PILOT_OPTIONS', payload: newPilotsOptions });
} }
}, [pilots]); }, [pilots]);
@@ -71,21 +73,25 @@ const LogForm = () => {
<Controller <Controller
name="pilotId" name="pilotId"
control={control} control={control}
render={({ field: { onChange, value } }) => { render={({ field: { value } }) => {
return ( return (
<select <Select
className='select w-full'
aria-labelledby='pilot' aria-labelledby='pilot'
disabled={state.isDisabled} isDisabled={state.isDisabled}
onChange={onChange} fullWidth={true}
value={[value]} isRequired={true}
onSelectionChange={(keys: SharedSelection) => {
setValue('pilotId', keys.currentKey);
}}
selectedKeys={[value]}
size='lg'
> >
{state.pilotOptions?.map((pilotOption: { key: string; label: string, }) => { {state.pilotOptions?.map((pilotOption: { key: string; label: string, }) => {
return ( return (
<option key={pilotOption.key}>{pilotOption.label}</option> <SelectItem key={pilotOption.key}>{pilotOption.label}</SelectItem>
) )
})} })}
</select> </Select>
); );
}} }}
/> />
@@ -98,14 +104,21 @@ const LogForm = () => {
name="date" name="date"
control={control} control={control}
render={({ field: { onChange, value } }) => { render={({ field: { onChange, value } }) => {
const parsedAbsoluteDate = value ? parseAbsolute(value, getLocalTimeZone()) : value
return( return(
<input <DatePicker
type='date' aria-labelledby='date'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} isRequired={true}
onChange={onChange} onChange={(selectedDate) => {
value={value ? value.split('T')[0] : ''} let date = selectedDate as CalendarDate;
/>
setValue('date', date.toDate(getLocalTimeZone()).toISOString())
}}
size='lg'
value={parsedAbsoluteDate ? new CalendarDate(parsedAbsoluteDate.year, parsedAbsoluteDate.month, parsedAbsoluteDate.day) : value}
/>
) )
}} }}
/> />
@@ -118,11 +131,18 @@ const LogForm = () => {
name="aircraftMakeModel" name="aircraftMakeModel"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <Input
type='text' aria-labelledby='aircraftMakeModel'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={formState.errors.address ? 'danger' : undefined}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isRequired={true}
onChange={onChange} onChange={onChange}
size='lg'
value={value} value={value}
/> />
)} )}
@@ -138,11 +158,18 @@ const LogForm = () => {
name="aircraftIdentity" name="aircraftIdentity"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <Input
type='text' aria-labelledby='aircraftIdentity'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={formState.errors.address ? 'danger' : undefined}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isRequired={true}
onChange={onChange} onChange={onChange}
size='lg'
value={value} value={value}
/> />
)} )}
@@ -158,11 +185,18 @@ const LogForm = () => {
name="routeFrom" name="routeFrom"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <Input
type='text' aria-labelledby='routeFrom'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={formState.errors.address ? 'danger' : undefined}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isRequired={true}
onChange={onChange} onChange={onChange}
size='lg'
value={value} value={value}
/> />
)} )}
@@ -176,11 +210,18 @@ const LogForm = () => {
name="routeTo" name="routeTo"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <Input
type='text' aria-labelledby='routeTo'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={formState.errors.address ? 'danger' : undefined}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isRequired={true}
onChange={onChange} onChange={onChange}
size='lg'
value={value} value={value}
/> />
)} )}
@@ -194,11 +235,21 @@ const LogForm = () => {
name="durationOfFlight" name="durationOfFlight"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='durationOfFlight'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={formState.errors.address ? 'danger' : undefined}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isRequired={true}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -214,11 +265,21 @@ const LogForm = () => {
name="singleEngineLand" name="singleEngineLand"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='singleEngineLand'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={formState.errors.address ? 'danger' : undefined}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isRequired={true}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -232,11 +293,20 @@ const LogForm = () => {
name="simulatorAtd" name="simulatorAtd"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='simulaterAtd'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={formState.errors.address ? 'danger' : undefined}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -253,11 +323,22 @@ const LogForm = () => {
name="landingsDay" name="landingsDay"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='landingsDay'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -271,11 +352,22 @@ const LogForm = () => {
name="landingsNight" name="landingsNight"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='landingsNight'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -294,12 +386,24 @@ const LogForm = () => {
name="groundTrainingReceived" name="groundTrainingReceived"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='groundTrainingReceived'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
width='w-full'
/> />
)} )}
/> />
@@ -314,11 +418,22 @@ const LogForm = () => {
name="flightTrainingReceived" name="flightTrainingReceived"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='flightTrainingReceived'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -332,11 +447,22 @@ const LogForm = () => {
name="crossCountry" name="crossCountry"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='crossCountry'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -350,11 +476,22 @@ const LogForm = () => {
name="night" name="night"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='night'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -368,11 +505,22 @@ const LogForm = () => {
name="solo" name="solo"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='solo'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -386,11 +534,22 @@ const LogForm = () => {
name="pilotInCommand" name="pilotInCommand"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='pilotInCommand'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -407,11 +566,22 @@ const LogForm = () => {
name="instrumentActual" name="instrumentActual"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='instrumentActual'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -425,11 +595,22 @@ const LogForm = () => {
name="instrumentSimulated" name="instrumentSimulated"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='instrumentSimulated'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -445,11 +626,22 @@ const LogForm = () => {
name="instrumentApproaches" name="instrumentApproaches"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='instrumentApproaches'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -463,11 +655,22 @@ const LogForm = () => {
name="instrumentHolds" name="instrumentHolds"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='instrumentHolds'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -481,11 +684,23 @@ const LogForm = () => {
name="instrumentNavTrack" name="instrumentNavTrack"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<input <NumberInput
type='number' aria-labelledby='instrumentNavTrack'
className='input w-full' isDisabled={state.isDisabled}
disabled={state.isDisabled} color={
formState.errors.address ? 'danger' : undefined
}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
fullWidth={true}
isWheelDisabled={state.isDisabled}
onChange={onChange} onChange={onChange}
radius='lg'
size='sm'
type="number"
value={value} value={value}
/> />
)} )}
@@ -501,11 +716,19 @@ const LogForm = () => {
name="notes" name="notes"
control={control} control={control}
render={({ field: { onChange, value } }) => ( render={({ field: { onChange, value } }) => (
<textarea <Textarea
className='textarea w-full' aria-labelledby='notes'
disabled={state.isDisabled} isDisabled={state.isDisabled}
color={formState.errors.address ? 'danger' : undefined}
errorMessage={
formState.errors.address
? formState.errors.address.message?.toString()
: undefined
}
fullWidth={true}
onChange={onChange} onChange={onChange}
></textarea> value={value}
/>
)} )}
/> />
</div> </div>

View File

@@ -1,9 +1,13 @@
import { Selection } from "@heroui/react";
import { Alert } from "../../interfaces/Alert.interface"; import { Alert } from "../../interfaces/Alert.interface";
export interface LogFormState { export interface LogFormState {
alert: Alert | undefined; alert: Alert | undefined;
experienceSelectedKeys: Selection;
instrumentSelectedKeys: Selection;
isDisabled: boolean; isDisabled: boolean;
isLoading: boolean; isLoading: boolean;
landingsSelectedKeys: Selection;
pilotOptions: { key: string; label: string; }[]; pilotOptions: { key: string; label: string; }[];
selectedPilotName: string; selectedPilotName: string;
} }

View File

@@ -1,17 +1,24 @@
import { Alert } from '../../interfaces/Alert.interface'; import { Alert } from '../../interfaces/Alert.interface';
import { LogFormState } from './LogFormState.interface'; import { LogFormState } from './LogFormState.interface';
import { Selection } from '@heroui/react';
type Action = type Action =
| { type: 'SET_ALERT'; payload: Alert | undefined } | { type: 'SET_ALERT'; payload: Alert | undefined }
| { type: 'SET_EXPERIENCE_SELECTED_KEYS'; payload: Selection }
| { type: 'SET_INSTRUMENT_SELECTED_KEYS'; payload: Selection }
| { type: 'SET_IS_DISABLED'; payload: boolean } | { type: 'SET_IS_DISABLED'; payload: boolean }
| { type: 'SET_IS_LOADING'; payload: boolean } | { type: 'SET_IS_LOADING'; payload: boolean }
| { type: 'SET_LANDINGS_SELECTED_KEYS'; payload: Selection }
| { type: 'SET_PILOT_OPTIONS'; payload: { key: string, label: string; }[] } | { type: 'SET_PILOT_OPTIONS'; payload: { key: string, label: string; }[] }
| { type: 'SET_SELECTED_PILOT_NAME'; payload: string }; | { type: 'SET_SELECTED_PILOT_NAME'; payload: string };
export const initialState: LogFormState = { export const initialState: LogFormState = {
alert: undefined, alert: undefined,
experienceSelectedKeys: new Set([]),
instrumentSelectedKeys: new Set([]),
isDisabled: false, isDisabled: false,
isLoading: true, isLoading: true,
landingsSelectedKeys: new Set(['1']),
pilotOptions: [], pilotOptions: [],
selectedPilotName: '' selectedPilotName: ''
}; };
@@ -27,18 +34,36 @@ export const reducer = (
alert: action.payload alert: action.payload
}; };
} }
case 'SET_EXPERIENCE_SELECTED_KEYS': {
return {
...state,
experienceSelectedKeys: action.payload
}
}
case 'SET_IS_DISABLED': { case 'SET_IS_DISABLED': {
return { return {
...state, ...state,
isDisabled: action.payload isDisabled: action.payload
}; };
} }
case 'SET_INSTRUMENT_SELECTED_KEYS': {
return {
...state,
instrumentSelectedKeys: action.payload
}
}
case 'SET_IS_LOADING': { case 'SET_IS_LOADING': {
return { return {
...state, ...state,
isLoading: action.payload isLoading: action.payload
}; };
} }
case 'SET_LANDINGS_SELECTED_KEYS': {
return {
...state,
landingsSelectedKeys: action.payload
}
}
case 'SET_PILOT_OPTIONS': { case 'SET_PILOT_OPTIONS': {
return { return {
...state, ...state,

View File

@@ -1,8 +1,10 @@
import { useEffect, useReducer } from 'react'; import { Key, useEffect, useReducer } from 'react';
import LogForm from '../logForm/LogForm';
import { initialState, reducer } from './reducer'; import { initialState, reducer } from './reducer';
import { AxiosError, AxiosResponse } from 'axios'; import { AxiosError, AxiosResponse } from 'axios';
import { FormMode } from '../../enums/formMode'; import { FormMode } from '../../enums/formMode';
import { authColumns, unauthColumns } from './columns'; import { authColumns, unauthColumns } from './columns';
import ActionMenu from '../actionMenu/ActionMenu';
import ConfirmationDialog from '../confirmationDialog/ConfirmationDialog'; import ConfirmationDialog from '../confirmationDialog/ConfirmationDialog';
import { LogbookEntry } from './LogbookEntry.interface'; import { LogbookEntry } from './LogbookEntry.interface';
import LogbookCard from '../logbookCard/LogbookCard'; import LogbookCard from '../logbookCard/LogbookCard';
@@ -12,12 +14,12 @@ import { useUserRole } from '../../hooks/userRole/UseUserRole';
import { UserRole } from '../../enums/userRole'; 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 { Table, TableHeader, TableBody, TableColumn, Dropdown, DropdownTrigger, Button, DropdownSection, DropdownMenu, DropdownItem, Alert, TableRow, TableCell } from '@heroui/react';
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, faMapLocationDot } from '@fortawesome/free-solid-svg-icons'
import { CellContext, ColumnDef, flexRender, getCoreRowModel, getPaginationRowModel, HeaderContext, useReactTable } from '@tanstack/react-table'; import { CellContext, ColumnDef, flexRender, getCoreRowModel, getPaginationRowModel, HeaderContext, 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';
const Logbook: React.FC<unknown> = () => { const Logbook: React.FC<unknown> = () => {
const [state, dispatch] = useReducer(reducer, initialState); const [state, dispatch] = useReducer(reducer, initialState);
@@ -26,6 +28,7 @@ const Logbook: React.FC<unknown> = () => {
const { userRole } = useUserRole(); const { userRole } = useUserRole();
const { screenSize } = useBreakpoints(); const { screenSize } = useBreakpoints();
const columnTotal = (info: HeaderContext<LogbookEntry, unknown>): number => { const columnTotal = (info: HeaderContext<LogbookEntry, unknown>): number => {
const blah = info.table
const values: number[] = info.table.getPaginationRowModel().rows.map((row: any) => Number(row.getValue(info.column.id))).filter((value: any) => !Number.isNaN(value)); const values: number[] = info.table.getPaginationRowModel().rows.map((row: any) => Number(row.getValue(info.column.id))).filter((value: any) => !Number.isNaN(value));
let total: number = 0; let total: number = 0;
@@ -66,17 +69,13 @@ const Logbook: React.FC<unknown> = () => {
id: 'route', id: 'route',
header: 'Route of Flight', header: 'Route of Flight',
meta: { meta: {
className: 'border-l border-base-300', headerAlign: 'center'
headerAlign: 'text-center'
}, },
columns: [ columns: [
{ {
id: 'routeFrom', id: 'routeFrom',
accessorKey: 'routeFrom', accessorKey: 'routeFrom',
header: 'From', header: 'From'
meta: {
className: 'border-l border-base-300',
}
}, },
{ {
id: 'routeTo', id: 'routeTo',
@@ -90,9 +89,8 @@ const Logbook: React.FC<unknown> = () => {
accessorKey: 'durationOfFlight', accessorKey: 'durationOfFlight',
header: 'Duration Of Flight', header: 'Duration Of Flight',
meta: { meta: {
align: 'text-right', align: 'right',
className: 'border-l border-base-300', headerAlign: 'right'
headerAlign: 'text-right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '', info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '',
@@ -101,33 +99,51 @@ const Logbook: React.FC<unknown> = () => {
const notes: ColumnDef<LogbookEntry> = { const notes: ColumnDef<LogbookEntry> = {
id: 'notes', id: 'notes',
accessorKey: 'notes', accessorKey: 'notes',
header: 'Notes', header: 'Notes'
meta: {
className: 'border-l border-base-300',
}
} }
const actions: ColumnDef<LogbookEntry> = { const actions: ColumnDef<LogbookEntry> = {
id: 'actions', id: 'actions',
header: 'Actions', header: 'Actions',
meta: { meta: {
align: 'text-center', align: 'center',
className: 'border-l border-base-300', headerAlign: 'center'
headerAlign: 'text-center'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => { cell: (info: CellContext<LogbookEntry, unknown>) => {
return ( return (
<div className='dropdown dropdown-end'> <Dropdown>
<div tabIndex={0} role='button' className='btn btn-ghost'><FontAwesomeIcon icon={faEllipsisVertical} /></div> <DropdownTrigger>
<ul tabIndex={-1} className="dropdown-content menu bg-base-100 rounded-box z-1 w-52 p-2 shadow-sm border border-base-300"> <Button isIconOnly variant='light' size='lg'>
{isUserLoggedIn && userRole === UserRole.WRITE && <FontAwesomeIcon icon={faEllipsisVertical} />
<li><a onClick={() => onOpenCloseDrawer(FormMode.EDIT, info.row.original.id)}><FontAwesomeIcon icon={faPen} />Edit</a></li> </Button>
} </DropdownTrigger>
<li><a onClick={() => onOpenCloseDrawer(FormMode.VIEW, info.row.original.id)}><FontAwesomeIcon icon={faEye} />View</a></li> <DropdownMenu>
{isUserLoggedIn && userRole === UserRole.WRITE && <DropdownSection showDivider>
<li><a onClick={() => onDeleteLog(info.row.original.id)}><FontAwesomeIcon icon={faTrash} />Delete</a></li> <DropdownItem
} key='edit'
</ul> onPress={() => onOpenCloseDrawer(FormMode.EDIT, info.row.original.id)}
</div> startContent={<FontAwesomeIcon icon={faPen} />}
>
Edit
</DropdownItem>
<DropdownItem
key='view'
onPress={() => onOpenCloseDrawer(FormMode.VIEW, info.row.original.id)}
startContent={<FontAwesomeIcon icon={faEye} />}
>
View
</DropdownItem>
</DropdownSection>
<DropdownSection>
<DropdownItem
key='Delete'
onPress={() => onDeleteLog(info.row.original.id)}
startContent={<FontAwesomeIcon icon={faTrash} />}
>
Delete
</DropdownItem>
</DropdownSection>
</DropdownMenu>
</Dropdown>
) )
} }
} }
@@ -157,8 +173,8 @@ const Logbook: React.FC<unknown> = () => {
accessorKey: 'singleEngineLand', accessorKey: 'singleEngineLand',
header: 'Single Engine Land', header: 'Single Engine Land',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '', info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '',
@@ -168,8 +184,7 @@ const Logbook: React.FC<unknown> = () => {
id: 'landings', id: 'landings',
header: 'Landings', header: 'Landings',
meta: { meta: {
className: 'border-l border-base-300', headerAlign: 'center'
headerAlign: 'text-center'
}, },
columns: [ columns: [
{ {
@@ -178,9 +193,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Day', header: 'Day',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info) : '',
meta: { meta: {
align: 'text-right', align: 'right',
className: 'border-l border-base-300', headerAlign: 'right'
headerAlign: 'text-right'
} }
}, },
{ {
@@ -189,8 +203,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Night', header: 'Night',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
} }
} }
] ]
@@ -199,8 +213,7 @@ const Logbook: React.FC<unknown> = () => {
id: 'instrument', id: 'instrument',
header: 'Instrument', header: 'Instrument',
meta: { meta: {
className: 'border-l border-base-300', headerAlign: 'center'
headerAlign: 'text-center'
}, },
columns: [ columns: [
{ {
@@ -209,9 +222,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Actual', header: 'Actual',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
className: 'border-l border-base-300', headerAlign: 'right'
headerAlign: 'text-right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '', info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '',
@@ -222,8 +234,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Simulated', header: 'Simulated',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -234,8 +246,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Approaches', header: 'Approaches',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
} }
}, },
{ {
@@ -244,8 +256,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Holds', header: 'Holds',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
} }
}, },
{ {
@@ -254,8 +266,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Nav/Track', header: 'Nav/Track',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
} }
} }
] ]
@@ -264,8 +276,7 @@ const Logbook: React.FC<unknown> = () => {
id: 'experienceTraining', id: 'experienceTraining',
header: 'Type of pilot experience or training', header: 'Type of pilot experience or training',
meta: { meta: {
className: 'border-l border-base-300', headerAlign: 'center'
headerAlign: 'text-center'
}, },
columns: [ columns: [
{ {
@@ -274,9 +285,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Ground Training Received', header: 'Ground Training Received',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
className: 'border-l border-base-300', headerAlign: 'right'
headerAlign: 'text-right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -287,8 +297,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Flight Training Received', header: 'Flight Training Received',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -299,8 +309,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Cross Country', header: 'Cross Country',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -311,8 +321,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Night', header: 'Night',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -323,8 +333,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Solo', header: 'Solo',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -335,8 +345,8 @@ const Logbook: React.FC<unknown> = () => {
header: 'Pilot In Command', header: 'Pilot In Command',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -362,14 +372,14 @@ const Logbook: React.FC<unknown> = () => {
dispatch({ type: 'SET_ALERT', payload: undefined}) dispatch({ type: 'SET_ALERT', payload: undefined})
} }
} else { } else {
dispatch({ type: 'SET_ALERT', payload: { severity: 'info', message: 'No logbook entries found.'}}) dispatch({ type: 'SET_ALERT', payload: { severity: 'default', message: 'No logbook entries found.'}})
} }
} catch (error) { } catch (error) {
const axiosError = error as AxiosError; const axiosError = error as AxiosError;
dispatch({ dispatch({
type: 'SET_ALERT', type: 'SET_ALERT',
payload: { severity: 'error', message: `Loading of logbook entries failed with the following message: ${axiosError.message}`} payload: { severity: 'danger', message: `Loading of logbook entries failed with the following message: ${axiosError.message}`}
}); });
} finally { } finally {
dispatch({ type: 'SET_IS_LOADING', payload: false }); dispatch({ type: 'SET_IS_LOADING', payload: false });
@@ -427,7 +437,7 @@ const Logbook: React.FC<unknown> = () => {
dispatch({ dispatch({
type: 'SET_ALERT', type: 'SET_ALERT',
payload: { severity: 'error', message: `Loading of logbook entries failed with the following message: ${axiosError.message}`} payload: { severity: 'danger', message: `Loading of logbook entries failed with the following message: ${axiosError.message}`}
}); });
} finally { } finally {
dispatch({ type: 'SET_IS_CONFIRMATION_DIALOG_LOADING', payload: false }); dispatch({ type: 'SET_IS_CONFIRMATION_DIALOG_LOADING', payload: false });
@@ -493,52 +503,44 @@ const Logbook: React.FC<unknown> = () => {
</div> </div>
<div className='col-span-2 justify-self-end self-center'> <div className='col-span-2 justify-self-end self-center'>
{userRole === UserRole.WRITE && {userRole === UserRole.WRITE &&
// <Button <Button
// color='primary' color='primary'
// onPress={() => onOpenCloseDrawer(FormMode.ADD)} onPress={() => onOpenCloseDrawer(FormMode.ADD)}
// startContent={<FontAwesomeIcon icon={faAdd} />} startContent={<FontAwesomeIcon icon={faAdd} />}
// data-testid="pilot-add-button" data-testid="pilot-add-button"
// >
// Add Entry
// </Button>
<button className='btn btn-primary'
onClick={() => onOpenCloseDrawer(FormMode.ADD)}
> >
<FontAwesomeIcon icon={faAdd} />
Add Entry Add Entry
</button> </Button>
} }
</div> </div>
{!state.isLoading && state.alert && ( {!state.isLoading && state.alert && (
<div className='col-span-12 mb-5'> <div className='col-span-12 mb-5'>
<Alert <Alert
className='mb-5'
onClose={() => onClose={() =>
dispatch({ type: 'SET_ALERT', payload: undefined }) dispatch({ type: 'SET_ALERT', payload: undefined })
} }
severity={'info'} color={'default'}
> title={state.alert.message}
{state.alert.message} />
</Alert>
</div> </div>
)} )}
{!state.isLoading && ( {!state.isLoading && (
<div className='col-span-12 p-5 bg-base-100 border border-base-100 rounded-lg'> <div className='col-span-12'>
{state.entries.length > 0 && screenSize !== ScreenSize.SM && ( {state.entries.length > 0 && screenSize !== ScreenSize.SM && (
<div className='overflow-x-auto'> <div className='p-4 z-0 flex flex-col relative justify-between gap-4 bg-content1 overflow-auto shadow-small rounded-large w-full'>
<table className='table min-w-full h-auto table-auto w-full'> <table className='min-w-full h-auto table-auto w-full'>
<thead className='bg-base-200'> <thead className='[&>tr]:first:rounded-lg'>
{table.getHeaderGroups().map((headerGroup, headerGroupIndex) => ( {table.getHeaderGroups().map((headerGroup) => (
<tr className='group/tr outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2' key={headerGroup.id}> <tr className='group/tr outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2' key={headerGroup.id}>
{headerGroup.headers.map((header, headerIndex) => { {headerGroup.headers.map((header) => {
return ( return (
<th <th
className={`${header.column.columnDef.meta?.className ? header.column.columnDef.meta?.className : ''} group/th px-3 h-10 align-middle whitespace-nowrap text-foreground-500 text-tiny font-semibold ${headerGroupIndex === 0 ? 'first:rounded-tl-lg last:rounded-tr-lg' : ''} ${headerGroupIndex === table.getHeaderGroups().length - 1 ? 'first:rounded-bl-lg last:rounded-br-lg' : ''} data-[sortable=true]:cursor-pointer data-[hover=true]:text-foreground-400 outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2 text-start`} className={`${header.column.columnDef.meta?.align ? textAlignment[header.column.columnDef.meta?.align] : ''} group/th px-3 h-10 align-middle bg-default-100 whitespace-nowrap text-foreground-500 text-tiny font-semibold first:rounded-s-lg last:rounded-e-lg data-[sortable=true]:cursor-pointer data-[hover=true]:text-foreground-400 outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2 text-start`}
colSpan={header.colSpan} colSpan={header.colSpan}
key={header.id} key={header.id}
> >
{header.isPlaceholder ? null : ( {header.isPlaceholder ? null : (
<div className={`${header.column.columnDef.meta?.headerAlign ? header.column.columnDef.meta?.headerAlign : ''}`}> <div>
{flexRender( {flexRender(
header.column.columnDef.header, header.column.columnDef.header,
header.getContext() header.getContext()
@@ -564,15 +566,13 @@ const Logbook: React.FC<unknown> = () => {
{row.getVisibleCells().map((cell) => { {row.getVisibleCells().map((cell) => {
return ( return (
<td <td
className={`py-2 px-3 relative align-middle whitespace-normal text-small font-normal [&>*]:z-1 [&>*]:relative outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2 before:pointer-events-none before:content-[''] before:absolute before:z-0 before:inset-0 before:opacity-0 data-[selected=true]:before:opacity-100 group-data-[disabled=true]/tr:text-foreground-300 group-data-[disabled=true]/tr:cursor-not-allowed before:bg-default/60 data-[selected=true]:text-default-foreground first:before:rounded-s-lg last:before:rounded-e-lg text-start`} className={`${cell.column.columnDef.meta?.align ? textAlignment[cell.column.columnDef.meta?.align] : ''} py-2 px-3 relative align-middle whitespace-normal text-small font-normal [&>*]:z-1 [&>*]:relative outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2 before:pointer-events-none before:content-[''] before:absolute before:z-0 before:inset-0 before:opacity-0 data-[selected=true]:before:opacity-100 group-data-[disabled=true]/tr:text-foreground-300 group-data-[disabled=true]/tr:cursor-not-allowed before:bg-default/60 data-[selected=true]:text-default-foreground first:before:rounded-s-lg last:before:rounded-e-lg text-start`}
key={cell.id} key={cell.id}
> >
<div className={`${cell.column.columnDef.meta?.align ? cell.column.columnDef.meta?.align : ''}`}> {flexRender(
{flexRender( cell.column.columnDef.cell,
cell.column.columnDef.cell, cell.getContext()
cell.getContext() )}
)}
</div>
</td> </td>
); );
})} })}
@@ -581,7 +581,7 @@ const Logbook: React.FC<unknown> = () => {
})} })}
</> </>
</tbody> </tbody>
<thead className='[&>tr]:first:rounded-lg bg-base-200'> <thead className='[&>tr]:first:rounded-lg'>
{table.getFooterGroups().map((footerGroup, index) => { {table.getFooterGroups().map((footerGroup, index) => {
if (index === 0) { if (index === 0) {
return ( return (
@@ -591,16 +591,14 @@ const Logbook: React.FC<unknown> = () => {
<td <td
className='group/th px-3 h-10 align-middle bg-default-100 whitespace-nowrap text-foreground-500 text-tiny font-semibold first:rounded-s-lg last:rounded-e-lg data-[sortable=true]:cursor-pointer data-[hover=true]:text-foreground-400 outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2 text-start' className='group/th px-3 h-10 align-middle bg-default-100 whitespace-nowrap text-foreground-500 text-tiny font-semibold first:rounded-s-lg last:rounded-e-lg data-[sortable=true]:cursor-pointer data-[hover=true]:text-foreground-400 outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2 text-start'
key={header.id} key={header.id}
align={header.column.columnDef.meta?.align}
> >
<div className={`${header.column.columnDef.meta?.headerAlign ? header.column.columnDef.meta?.headerAlign : ''}`}> {header.isPlaceholder
{header.isPlaceholder ? null
? null : flexRender(
: flexRender( header.column.columnDef.footer,
header.column.columnDef.footer, header.getContext()
header.getContext() )}
)
}
</div>
</td> </td>
); );
})} })}
@@ -643,6 +641,14 @@ const Logbook: React.FC<unknown> = () => {
title="Confirm Delete" title="Confirm Delete"
/> />
)} )}
{/* {state.isTracksOpen &&
<LogTracks
isDrawerOpen={state.isTracksOpen}
mode={state.tracksMode}
onOpenClose={(mode) => onOpenCloseTracks(mode)}
selectedLogId={logbookContext.state.selectedLogId}
/>
} */}
</> </>
); );
}; };

View File

@@ -48,8 +48,7 @@ const route: ColumnDef<LogbookEntry> = {
id: 'route', id: 'route',
header: 'Route of Flight', header: 'Route of Flight',
meta: { meta: {
headerAlign: 'text-center', headerAlign: 'center'
className: 'border-l border-base-400'
}, },
columns: [ columns: [
{ {
@@ -69,8 +68,8 @@ const durationOfFlight: ColumnDef<LogbookEntry> = {
accessorKey: 'durationOfFlight', accessorKey: 'durationOfFlight',
header: 'Duration Of Flight', header: 'Duration Of Flight',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '', info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '',
@@ -107,8 +106,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
accessorKey: 'singleEngineLand', accessorKey: 'singleEngineLand',
header: 'Single Engine Land', header: 'Single Engine Land',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '', info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '',
@@ -118,7 +117,7 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
id: 'landings', id: 'landings',
header: 'Landings', header: 'Landings',
meta: { meta: {
headerAlign: 'text-center' headerAlign: 'center'
}, },
columns: [ columns: [
{ {
@@ -127,8 +126,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Day', header: 'Day',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
} }
}, },
{ {
@@ -137,8 +136,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Night', header: 'Night',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
} }
} }
] ]
@@ -147,7 +146,7 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
id: 'instrument', id: 'instrument',
header: 'Instrument', header: 'Instrument',
meta: { meta: {
headerAlign: 'text-center' headerAlign: 'center'
}, },
columns: [ columns: [
{ {
@@ -156,8 +155,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Actual', header: 'Actual',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '', info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '',
@@ -168,8 +167,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Simulated', header: 'Simulated',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -180,8 +179,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Approaches', header: 'Approaches',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
} }
}, },
{ {
@@ -190,8 +189,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Holds', header: 'Holds',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
} }
}, },
{ {
@@ -200,8 +199,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Nav/Track', header: 'Nav/Track',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
} }
} }
] ]
@@ -210,7 +209,7 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
id: 'experienceTraining', id: 'experienceTraining',
header: 'Type of pilot experience or training', header: 'Type of pilot experience or training',
meta: { meta: {
headerAlign: 'text-center' headerAlign: 'center'
}, },
columns: [ columns: [
{ {
@@ -219,8 +218,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Ground Training Received', header: 'Ground Training Received',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -231,8 +230,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Flight Training Received', header: 'Flight Training Received',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -243,8 +242,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Cross Country', header: 'Cross Country',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -255,8 +254,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Night', header: 'Night',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -267,8 +266,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Solo', header: 'Solo',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''
@@ -279,8 +278,8 @@ export const authColumns: ColumnDef<LogbookEntry>[] = [
header: 'Pilot In Command', header: 'Pilot In Command',
footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '', footer: (info: HeaderContext<LogbookEntry, unknown>) => columnTotal(info) > 0 ? columnTotal(info).toFixed(1) : '',
meta: { meta: {
align: 'text-right', align: 'right',
headerAlign: 'text-right' headerAlign: 'right'
}, },
cell: (info: CellContext<LogbookEntry, unknown>) => cell: (info: CellContext<LogbookEntry, unknown>) =>
info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : '' info.getValue() ? parseFloat(info.getValue() as string).toFixed(1) : ''

View File

@@ -1,3 +1,4 @@
import { Accordion, AccordionItem, Card, CardBody, CardHeader } from '@heroui/react'
import { LogbookCardProps } from "./LogbookCardProps.interface"; import { LogbookCardProps } from "./LogbookCardProps.interface";
import TrackMap from "../trackMap/TrackMap"; import TrackMap from "../trackMap/TrackMap";
@@ -9,10 +10,12 @@ const LogbookCard = ({ logs, mode, onDelete, onOpenCloseForm }: LogbookCardProps
const formattedDate: string = `${date.getMonth()}/${date.getDate()}/${date.getFullYear()}`; const formattedDate: string = `${date.getMonth()}/${date.getDate()}/${date.getFullYear()}`;
return ( return (
<div className='card bg-base-100 border border-base-300 p-2'> <div>
<div className='card-body' key={log.id}> <Card className='p-4' key={log.id}>
<h2 className='card-title font-bold text-2xl'>{formattedDate}</h2> <CardHeader>
<div> <h2 className='font-bold text-2xl'>{formattedDate}</h2>
</CardHeader>
<CardBody>
{mode === 'flights' && log.tracks && log.tracks.length > 0 && {mode === 'flights' && log.tracks && log.tracks.length > 0 &&
<div className='mb-5'> <div className='mb-5'>
<TrackMap <TrackMap
@@ -22,50 +25,49 @@ const LogbookCard = ({ logs, mode, onDelete, onOpenCloseForm }: LogbookCardProps
/> />
</div> </div>
} }
</div> <Accordion variant='bordered'>
<div className='collapse collapse-arrow bg-base-100 border-base-300 border'> <AccordionItem key='1' title='Details'>
<input type='radio' name='details-accordion' /> <div className='grid grid-cols-12 gap-3 mr-[30%] ml-[30%] mt-4 mb-4'>
<div className='collapse-title font-semibold'>Details</div> <div className='col-span-6 font-bold'>
<div className='collapse-content'> <span>Aircraft Make and Model</span>
<div className='grid grid-cols-12 gap-3 mr-[30%] ml-[30%] mt-4 mb-4'> </div>
<div className='col-span-6 font-bold'> <div className='col-span-6'>
<span>Aircraft Make and Model</span> <span>{log.aircraftMakeModel}</span>
</div>
<div className='col-span-6 font-bold'>
<span>Route From</span>
</div>
<div className='col-span-6'>
<span>{log.routeFrom}</span>
</div>
<div className='col-span-6 font-bold'>
<span>Route To</span>
</div>
<div className='col-span-6'>
<span>{log.routeTo}</span>
</div>
<div className='col-span-6 font-bold'>
<span>Duration Of Flight</span>
</div>
<div className='col-span-6'>
<span>{log.durationOfFlight}</span>
</div>
{log.notes &&
<>
<div className='col-span-6 font-bold'>
<span>Notes</span>
</div>
<div className='col-span-6'>
<span>{log.notes}</span>
</div>
</>
}
</div> </div>
<div className='col-span-6'> </AccordionItem>
<span>{log.aircraftMakeModel}</span> </Accordion>
</div>
<div className='col-span-6 font-bold'> </CardBody>
<span>Route From</span> </Card>
</div>
<div className='col-span-6'>
<span>{log.routeFrom}</span>
</div>
<div className='col-span-6 font-bold'>
<span>Route To</span>
</div>
<div className='col-span-6'>
<span>{log.routeTo}</span>
</div>
<div className='col-span-6 font-bold'>
<span>Duration Of Flight</span>
</div>
<div className='col-span-6'>
<span>{log.durationOfFlight}</span>
</div>
{log.notes &&
<>
<div className='col-span-6 font-bold'>
<span>Notes</span>
</div>
<div className='col-span-6'>
<span>{log.notes}</span>
</div>
</>
}
</div>
</div>
</div>
</div>
</div> </div>
) )
})} })}

View File

@@ -1,7 +1,7 @@
import { Alert, Button, Drawer, DrawerBody, DrawerContent, DrawerFooter, DrawerHeader, Tab, Tabs } from "@heroui/react";
import { LogbookDrawerProps } from "./LogbookDrawerProps.interface"; import { LogbookDrawerProps } from "./LogbookDrawerProps.interface";
import LogForm from "../logForm/LogForm"; import LogForm from "../logForm/LogForm";
import TracksForm from "../tracksForm/TracksForm"; import TracksForm from "../tracksForm/TracksForm";
import Alert from '../alert/Alert';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faClock, faMapLocationDot, faSave, faXmark } from "@fortawesome/free-solid-svg-icons"; import { faClock, faMapLocationDot, faSave, faXmark } from "@fortawesome/free-solid-svg-icons";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
@@ -9,10 +9,10 @@ import { FormMode } from "../../enums/formMode";
import httpClient from "../../httpClient/httpClient"; import httpClient from "../../httpClient/httpClient";
import { AxiosError } from "axios"; import { AxiosError } from "axios";
import { useLogbookContext } from "../../hooks/logbookContext/UseLogbookContext"; import { useLogbookContext } from "../../hooks/logbookContext/UseLogbookContext";
import { useState } from "react"; import { Key, useState } from "react";
const LogbookDrawer = ({ onOpenClose }: LogbookDrawerProps) => { const LogbookDrawer = ({ onOpenClose }: LogbookDrawerProps) => {
const [activeTab, setActiveTab] = useState<string>('time'); const [activeTab, setActiveTab] = useState<Key>('time');
const defaultValues = { const defaultValues = {
pilotId: '', pilotId: '',
date: null, date: null,
@@ -63,107 +63,111 @@ const LogbookDrawer = ({ onOpenClose }: LogbookDrawerProps) => {
} catch (error) { } catch (error) {
const axiosError = error as AxiosError; const axiosError = error as AxiosError;
logbookContext.dispatch({ type: 'SET_FORM_ALERT', payload: { severity: 'error', message: axiosError.message }}); logbookContext.dispatch({ type: 'SET_FORM_ALERT', payload: { severity: 'danger', message: axiosError.message }});
} finally { } finally {
logbookContext.dispatch({ type: 'SET_IS_FORM_LOADING', payload: false }); logbookContext.dispatch({ type: 'SET_IS_FORM_LOADING', payload: false });
} }
}; };
const onSelectedKeyChanged = (tab: string) => { const onSelectedKeyChanged = (key: React.Key) => {
setActiveTab(tab) setActiveTab(key)
} }
return ( return (
<div className='drawer drawer-end' <Drawer
// closeButton={ closeButton={
// <Button isIconOnly> <Button isIconOnly>
// <FontAwesomeIcon icon={faXmark} /> <FontAwesomeIcon icon={faXmark} />
// </Button> </Button>
// } }
// isOpen={logbookContext.state.isDrawerOpen} isOpen={logbookContext.state.isDrawerOpen}
// onClose={onCancel} onClose={onCancel}
> >
<input type='checkbox' className='drawer-toggle' onChange={() => {}} checked={logbookContext.state.isDrawerOpen} /> <DrawerContent>
<div className="drawer-side"> <FormProvider {...methods}>
<label <form className='prose max-w-none' onSubmit={methods.handleSubmit(onSubmit)} style={{ paddingBottom: '50px' }}>
htmlFor='my-drawer-1' <DrawerHeader>
aria-label='close-sidebar' {`${logbookContext.state.formMode.toString().toLowerCase().charAt(0).toUpperCase() + logbookContext.state.formMode.toString().slice(1).toLowerCase()} Entry`}
className='drawer-overlay' </DrawerHeader>
></label> <DrawerBody>
<div className='menu bg-base-100 text-base-content min-h-full p-4' style={{ width: '25%' }}> {logbookContext.state.formAlert && (
<FormProvider {...methods}> <div className='col-span-12'>
<form className='prose max-w-none' onSubmit={methods.handleSubmit(onSubmit)} style={{ paddingBottom: '50px' }}>
<h2>
{`${logbookContext.state.formMode.toString().toLowerCase().charAt(0).toUpperCase() + logbookContext.state.formMode.toString().slice(1).toLowerCase()} Entry`}
</h2>
{logbookContext.state.formAlert && (
<Alert <Alert
className='mb-5'
onClose={() => onClose={() =>
logbookContext.dispatch({ type: 'SET_FORM_ALERT', payload: undefined }) logbookContext.dispatch({ type: 'SET_FORM_ALERT', payload: undefined })
} }
severity={logbookContext.state.formAlert.severity} color={logbookContext.state.formAlert.severity}
> title={logbookContext.state.formAlert.message}
{logbookContext.state.formAlert.message} />
</Alert>
)}
<div className='tabs tabs-lift mb-5'>
<label className='tab'>
<input type='radio' name='my_tabs' defaultChecked={true} />
<FontAwesomeIcon className='mr-1'icon={faClock} />
Time
</label>
<div className='tab-content border-base-300 p-6'>
<LogForm />
</div>
{logbookContext.state.formMode !== FormMode.ADD &&
<>
<label className='tab'>
<input type='radio' name='my_tabs'/>
<FontAwesomeIcon className='mr-1' icon={faMapLocationDot} />
Tracks
</label>
<div className='tab-content border-base-300 p-6'>
<TracksForm />
</div>
</>
}
</div> </div>
{activeTab !== 'tracks' && )}
<div> <Tabs
<div className='grid grid-cols-12 gap-3'> color='default'
<div className='col-span-12 justify-self-end self-center'> fullWidth={true}
<button onSelectionChange={onSelectedKeyChanged}
className='btn' selectedKey={activeTab as string}
disabled={ variant='solid'
logbookContext.state.isFormDisabled && logbookContext.state.formMode.toString() !== FormMode.VIEW >
? logbookContext.state.isFormDisabled <Tab
: false key='time'
} title={
onClick={onCancel} <div className="flex items-center space-x-2">
> <FontAwesomeIcon icon={faClock} />
<FontAwesomeIcon icon={faXmark} /> <span>Time</span>
{logbookContext.state.formMode.toString() !== FormMode.VIEW ? 'Cancel' : 'Close'}
</button>
{logbookContext.state.formMode.toString() !== FormMode.VIEW && (
<button
className='btn btn-primary ml-2.5'
disabled={logbookContext.state.isFormDisabled}
type="submit"
>
<FontAwesomeIcon icon={faSave} />
Save
</button>
)}
</div>
</div> </div>
</div> }
>
<LogForm />
</Tab>
{logbookContext.state.formMode !== FormMode.ADD &&
<Tab
key='tracks'
title={
<div className="flex items-center space-x-2">
<FontAwesomeIcon icon={faMapLocationDot} />
<span>Tracks</span>
</div>
}
>
<TracksForm />
</Tab>
} }
</form> </Tabs>
</FormProvider> </DrawerBody>
</div> {activeTab !== 'tracks' &&
</div> <DrawerFooter>
</div> <div className='grid grid-cols-12 gap-3'>
<div className='col-span-12 justify-self-end self-center'>
<Button
disabled={
logbookContext.state.isFormDisabled && logbookContext.state.formMode.toString() !== FormMode.VIEW
? logbookContext.state.isFormDisabled
: false
}
startContent={<FontAwesomeIcon icon={faXmark} />}
onPress={onCancel}
>
{logbookContext.state.formMode.toString() !== FormMode.VIEW ? 'Cancel' : 'Close'}
</Button>
{logbookContext.state.formMode.toString() !== FormMode.VIEW && (
<Button
className='ml-[10px]'
color='primary'
disabled={logbookContext.state.isFormDisabled}
startContent={<FontAwesomeIcon icon={faSave} />}
type="submit"
>
Save
</Button>
)}
</div>
</div>
</DrawerFooter>
}
</form>
</FormProvider>
</DrawerContent>
</Drawer>
) )
} }

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react'; import { Key, useEffect, useState } from 'react';
import { useForm, Controller, FormProvider } from 'react-hook-form'; import { useForm, Controller, FormProvider } from 'react-hook-form';
import { IPilotFormProps } from './IPilotFormProps'; import { IPilotFormProps } from './IPilotFormProps';
import { AxiosError, AxiosResponse } from 'axios'; import { AxiosError, AxiosResponse } from 'axios';
@@ -9,6 +9,7 @@ import PilotFormEndorsements from '../pilotFormEndorsements/PilotFormEndorsement
import PilotFormMedical from '../pilotFormMedical/PilotFormMedical'; import PilotFormMedical from '../pilotFormMedical/PilotFormMedical';
import { useOidc } from '../../auth/oidcConfig'; import { useOidc } from '../../auth/oidcConfig';
import httpClient from '../../httpClient/httpClient'; import httpClient from '../../httpClient/httpClient';
import { Button, Drawer, DrawerHeader, DrawerContent, DrawerBody, DrawerFooter, Input, Autocomplete, AutocompleteItem, SelectItem, Select } from '@heroui/react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSave, faXmark } from '@fortawesome/free-solid-svg-icons'; import { faSave, faXmark } from '@fortawesome/free-solid-svg-icons';
import { states } from './states'; import { states } from './states';
@@ -44,6 +45,39 @@ const PilotForm: React.FC<IPilotFormProps> = ({
const [isDisabled, setIsDisabled] = useState<boolean>(false); const [isDisabled, setIsDisabled] = useState<boolean>(false);
const [isError, setIsError] = useState<boolean>(false); const [isError, setIsError] = useState<boolean>(false);
const onPeoplePickerSearch = async (
value: string
) => {
setIsPeoplePickerLoading(true);
setPeoplePickerValue(value)
try {
if (value !== '') {
const searchString: string = value;
const response: AxiosResponse = await httpClient.get(
`api/msgraph/search?search=${searchString}`
);
setPeoplePickerResults(response.data);
} else {
setPeoplePickerResults([]);
}
} catch (error) {
console.log(error);
} finally {
setIsPeoplePickerLoading(false);
}
};
const onPersonSelected = (userPrincipalName: string) => {
const person: Person | undefined = peoplePickerResults.find((person) => person.userPrincipalName === userPrincipalName as string);
methods.setValue('name', person?.displayName!);
methods.setValue('userId', person?.userPrincipalName!);
setPeoplePickerValue(person?.displayName!);
setPeoplePickerResults([])
};
const onCancel = () => { const onCancel = () => {
methods.reset(defaultValues); methods.reset(defaultValues);
onOpenClose(FormMode.CANCEL); onOpenClose(FormMode.CANCEL);
@@ -104,229 +138,245 @@ const PilotForm: React.FC<IPilotFormProps> = ({
}, [pilotId]); }, [pilotId]);
return ( return (
<div className='drawer drawer-end' <Drawer
// closeButton={ closeButton={
// <Button isIconOnly> <Button isIconOnly>
// <FontAwesomeIcon icon={faXmark} /> <FontAwesomeIcon icon={faXmark} />
// </Button> </Button>
// } }
// isOpen={isDrawerOpen} isOpen={isDrawerOpen}
// placement='right' placement='right'
// data-testid="pilot-drawer" data-testid="pilot-drawer"
// onClose={onCancel} onClose={onCancel}
// size='xl' size='xl'
> >
<input type='checkbox' className='drawer-toggle' onChange={() => {}} checked={isDrawerOpen} /> <DrawerContent>
<div className='drawer-side'> <FormProvider {...methods}>
<label <form className='prose max-w-none' onSubmit={methods.handleSubmit(onSubmit)} style={{ paddingBottom: '50px' }}>
htmlFor='my-drawer-1' <DrawerHeader>
aria-label='close-sidebar' {`${mode.toString().toLowerCase().charAt(0).toUpperCase() + mode.toString().slice(1).toLowerCase()} Pilot`}
className='drawer-overlay' </DrawerHeader>
></label> <DrawerBody>
<div className='menu bg-base-100 text-base-content min-h-full p-4' style={{ width: '25%' }}> <div className='grid grid-cols-12 gap-3'>
<FormProvider {...methods}> <div className='col-span-3 self-center'>
<form className='prose max-w-none' onSubmit={methods.handleSubmit(onSubmit)} style={{ paddingBottom: '50px' }}> <h6>Name *</h6>
<h2>
{`${mode.toString().toLowerCase().charAt(0).toUpperCase() + mode.toString().slice(1).toLowerCase()} Pilot`}
</h2>
<div className='grid grid-cols-12 gap-3'>
<div className='col-span-3 self-center'>
<span>Name *</span>
</div>
<div className='col-span-9'>
<Controller
name="name"
control={methods.control}
rules={{ required: 'A name is required' }}
render={({ field: { onChange, value } }) => (
<input
type='text'
className='input w-full'
disabled={isDisabled}
onChange={onChange}
value={value}
/>
)}
/>
</div>
{isUserLoggedIn &&
<>
<div className='col-span-3 self-center'>
<span>Address *</span>
</div>
<div className='col-span-9'>
<Controller
name="address"
control={methods.control}
rules={{ required: 'An address is required' }}
render={({ field: { onChange, value } }) => (
<input
type='text'
className='input w-full'
disabled={isDisabled}
onChange={onChange}
value={value}
/>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>City *</h6>
</div>
<div className='col-span-9'>
<Controller
name="city"
control={methods.control}
rules={{ required: 'A city is required' }}
render={({ field: { onChange, value } }) => (
<input
type='text'
className='input w-full'
disabled={isDisabled}
onChange={onChange}
value={value}
/>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>State *</h6>
</div>
<div className='col-span-9'>
<Controller
name="state"
control={methods.control}
rules={{ required: 'A state must be selected' }}
render={({ field: { onChange, value } }) => (
<select
className='select w-full'
onChange={onChange}
value={[value]}
>
{states.map((state) => (
<option key={state.value}>{state.label}</option>
))}
</select>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>Postal Code *</h6>
</div>
<div className='col-span-9'>
<Controller
name="postalCode"
control={methods.control}
rules={{ required: 'A postal code is required' }}
render={({ field: { onChange, value } }) => (
<input
type='text'
className='input w-full'
disabled={isDisabled}
onChange={onChange}
value={value}
/>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>Email</h6>
</div>
<div className='col-span-9'>
<Controller
name="email"
control={methods.control}
rules={{
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: 'Invalid email address'
}
}}
render={({ field: { onChange, value } }) => (
<input
type='text'
className='input w-full'
disabled={isDisabled}
onChange={onChange}
value={value}
/>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>Phone Number</h6>
</div>
<div className='col-span-9'>
<Controller
name="phone"
control={methods.control}
rules={{
pattern: {
value: /^[0-9]{3}[-\s\.][0-9]{3}[-\s\.][0-9]{4}$/i,
message: 'Enter phone number as 123-456-7890'
}
}}
render={({ field: { onChange, value } }) => (
<input
type='text'
className='input w-full'
disabled={isDisabled}
onChange={onChange}
value={value}
/>
)}
/>
</div>
</>
}
{/* {isAuthenticated &&
<Grid size={12}>
<PilotFormMedical
isDisabled={isDisabled}
/>
</Grid>
}
<Grid size={12}>
<PilotFormCertificates isDisabled={isDisabled} mode={mode} />
</Grid>
<Grid size={12}>
<PilotFormEndorsements isDisabled={isDisabled} mode={mode} />
</Grid> */}
{/* <div className='col-span-12 justify-self-end self-center'> */}
<div className='col-span-12 justify-self-end self-center'>
<button
className='btn'
disabled={
isDisabled && mode.toString() !== FormMode.VIEW
? isDisabled
: false
}
onClick={onCancel}
data-testid="pilot-cancel-button"
>
<FontAwesomeIcon icon={faXmark} />
{mode.toString() !== FormMode.VIEW ? 'Cancel' : 'Close'}
</button>
{mode.toString() !== FormMode.VIEW && (
<button
className='btn btn-primary ml-2.5'
disabled={isDisabled}
type="submit"
data-testid="pilot-save-button"
>
<FontAwesomeIcon icon={faSave} />
Save
</button>
)}
</div>
</div> </div>
</form> <div className='col-span-9'>
</FormProvider> <Autocomplete
</div> inputValue={peoplePickerValue}
</div> isLoading={isPeoplePickerLoading}
</div> items={peoplePickerResults}
onInputChange={onPeoplePickerSearch}
onSelectionChange={(key: Key | null) => onPersonSelected(key as string)}
>
{peoplePickerResults.map((person: Person) => (
<AutocompleteItem key={person.userPrincipalName}>
{person.displayName}
</AutocompleteItem>
))}
</Autocomplete>
</div>
{isUserLoggedIn &&
<>
<div className='col-span-3 self-center'>
<span>Address *</span>
</div>
<div className='col-span-9'>
<Controller
name="address"
control={methods.control}
rules={{ required: 'An address is required' }}
render={({ field: { onChange, value } }) => (
<Input
disabled={isDisabled}
color={methods.formState.errors.address ? 'danger' : undefined}
errorMessage={
methods.formState.errors.address
? methods.formState.errors.address.message
: undefined
}
fullWidth={true}
onChange={onChange}
value={value}
/>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>City *</h6>
</div>
<div className='col-span-9'>
<Controller
name="city"
control={methods.control}
rules={{ required: 'A city is required' }}
render={({ field: { onChange, value } }) => (
<Input
disabled={isDisabled}
color={methods.formState.errors.city ? 'danger' : undefined}
errorMessage={
methods.formState.errors.city
? methods.formState.errors.city.message
: undefined
}
fullWidth={true}
onChange={onChange}
value={value}
/>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>State *</h6>
</div>
<div className='col-span-9'>
<Controller
name="state"
control={methods.control}
rules={{ required: 'A state must be selected' }}
render={({ field: { onChange, value } }) => (
<Select
onChange={onChange}
selectedKeys={[value]}
>
{states.map((state) => (
<SelectItem key={state.value}>{state.label}</SelectItem>
))}
</Select>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>Postal Code *</h6>
</div>
<div className='col-span-9'>
<Controller
name="postalCode"
control={methods.control}
rules={{ required: 'A postal code is required' }}
render={({ field: { onChange, value } }) => (
<Input
disabled={isDisabled}
color={methods.formState.errors.postalCode ? 'danger' : undefined}
errorMessage={
methods.formState.errors.postalCode
? methods.formState.errors.postalCode.message
: undefined
}
fullWidth={true}
onChange={onChange}
value={value}
/>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>Email</h6>
</div>
<div className='col-span-9'>
<Controller
name="email"
control={methods.control}
rules={{
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: 'Invalid email address'
}
}}
render={({ field: { onChange, value } }) => (
<Input
disabled={isDisabled}
color={methods.formState.errors.email ? 'danger' : undefined}
errorMessage={
methods.formState.errors.email
? methods.formState.errors.email.message
: undefined
}
fullWidth={true}
onChange={onChange}
value={value}
/>
)}
/>
</div>
<div className='col-span-3 self-center'>
<h6>Phone Number</h6>
</div>
<div className='col-span-9'>
<Controller
name="phone"
control={methods.control}
rules={{
pattern: {
value: /^[0-9]{3}[-\s\.][0-9]{3}[-\s\.][0-9]{4}$/i,
message: 'Enter phone number as 123-456-7890'
}
}}
render={({ field: { onChange, value } }) => (
<Input
disabled={isDisabled}
color={methods.formState.errors.phone ? 'danger' : undefined}
errorMessage={
methods.formState.errors.phone
? methods.formState.errors.phone.message
: undefined
}
fullWidth={true}
onChange={onChange}
value={value}
/>
)}
/>
</div>
</>
}
{/* {isAuthenticated &&
<Grid size={12}>
<PilotFormMedical
isDisabled={isDisabled}
/>
</Grid>
}
<Grid size={12}>
<PilotFormCertificates isDisabled={isDisabled} mode={mode} />
</Grid>
<Grid size={12}>
<PilotFormEndorsements isDisabled={isDisabled} mode={mode} />
</Grid> */}
{/* <div className='col-span-12 justify-self-end self-center'> */}
{/* </div> */}
</div>
</DrawerBody>
<DrawerFooter>
<Button
disabled={
isDisabled && mode.toString() !== FormMode.VIEW
? isDisabled
: false
}
startContent={<FontAwesomeIcon icon={faXmark} />}
onPress={onCancel}
data-testid="pilot-cancel-button"
>
{mode.toString() !== FormMode.VIEW ? 'Cancel' : 'Close'}
</Button>
{mode.toString() !== FormMode.VIEW && (
<Button
color='primary'
disabled={isDisabled}
startContent={<FontAwesomeIcon icon={faSave} />}
type="submit"
data-testid="pilot-save-button"
>
Save
</Button>
)}
</DrawerFooter>
</form>
</FormProvider>
</DrawerContent>
</Drawer>
); );
}; };

View File

@@ -10,18 +10,14 @@ import { UserRole } from '../../enums/userRole';
import httpClient from '../../httpClient/httpClient' import httpClient from '../../httpClient/httpClient'
import { ScreenSize } from '../../enums/screenSize'; import { ScreenSize } from '../../enums/screenSize';
import { useBreakpoints } from '../../hooks/useBreakpoints/UseBreakpoints'; import { useBreakpoints } from '../../hooks/useBreakpoints/UseBreakpoints';
import { Alert, Button, Dropdown, DropdownItem, DropdownSection, Table, TableHeader, TableBody, TableColumn, TableRow, TableCell, DropdownTrigger, DropdownMenu } from '@heroui/react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faEllipsisVertical, faPen, faEye, faTrash, faPlus } from '@fortawesome/free-solid-svg-icons'; import { faEllipsisVertical, faPen, faEye, faTrash, faPlus } from '@fortawesome/free-solid-svg-icons'
import { CellContext, ColumnDef, flexRender, getCoreRowModel, getPaginationRowModel, useReactTable } from '@tanstack/react-table';
import { Pilot } from './Pilot.interface';
import Alert from '../alert/Alert';
import { useOidc } from '../../auth/oidcConfig';
const Pilots: React.FC<unknown> = () => { const Pilots: React.FC<unknown> = () => {
const [state, dispatch] = useReducer(reducer, initialState); const [state, dispatch] = useReducer(reducer, initialState);
const { userRole } = useUserRole(); const { userRole } = useUserRole();
const { screenSize } = useBreakpoints(); const { screenSize } = useBreakpoints()
const { isUserLoggedIn } = useOidc();
const getPilots = async () => { const getPilots = async () => {
try { try {
@@ -31,8 +27,6 @@ const Pilots: React.FC<unknown> = () => {
`api/pilots` `api/pilots`
); );
console.log(response)
if (response.data.length > 0) { if (response.data.length > 0) {
dispatch({ type: 'SET_PILOTS', payload: response.data }); dispatch({ type: 'SET_PILOTS', payload: response.data });
@@ -40,7 +34,7 @@ const Pilots: React.FC<unknown> = () => {
dispatch({ type: 'SET_ALERT', payload: undefined }) dispatch({ type: 'SET_ALERT', payload: undefined })
} }
} else { } else {
dispatch({ type: 'SET_ALERT', payload: { severity: 'info', message: 'No pilots found.' }}) dispatch({ type: 'SET_ALERT', payload: { severity: 'default', message: 'No pilots found.' }})
dispatch({ type: 'SET_PILOTS', payload: [] }); dispatch({ type: 'SET_PILOTS', payload: [] });
} }
} catch (error) { } catch (error) {
@@ -48,7 +42,7 @@ const Pilots: React.FC<unknown> = () => {
dispatch({ dispatch({
type: 'SET_ALERT', type: 'SET_ALERT',
payload: { severity: 'error', message: `Loading of pilots failed with the following message: ${axiosError.message}`} payload: { severity: 'danger', message: `Loading of pilots failed with the following message: ${axiosError.message}`}
}) })
} finally { } finally {
dispatch({ type: 'SET_IS_LOADING', payload: false }) dispatch({ type: 'SET_IS_LOADING', payload: false })
@@ -107,7 +101,7 @@ const Pilots: React.FC<unknown> = () => {
dispatch({ dispatch({
type: 'SET_ALERT', type: 'SET_ALERT',
payload: { severity: 'error', message: `Loading of logbook entries failed with the following message: ${axiosError.message}`} payload: { severity: 'danger', message: `Loading of logbook entries failed with the following message: ${axiosError.message}`}
}); });
} finally { } finally {
dispatch({ type: 'SET_IS_CONFIRMATION_DIALOG_LOADING', payload: false }); dispatch({ type: 'SET_IS_CONFIRMATION_DIALOG_LOADING', payload: false });
@@ -121,50 +115,64 @@ const Pilots: React.FC<unknown> = () => {
}); });
}; };
const columns: ColumnDef<Pilot>[]= [ const columns = [
{ {
id: 'name', id: 'name',
accessorKey: 'name', name: 'Name'
header: 'Name'
}, },
{ {
id: 'actions', id: 'actions',
header: 'Actions', name: 'Actions'
meta: {
align: 'text-center',
headerAlign: 'text-center'
},
cell: (info: CellContext<Pilot, unknown>) => {
return (
<div className='dropdown dropdown-end'>
<div tabIndex={0} role='button' className='btn btn-ghost'><FontAwesomeIcon icon={faEllipsisVertical} /></div>
<ul tabIndex={-1} className="dropdown-content menu bg-base-100 rounded-box z-1 w-52 p-2 shadow-sm border border-base-300">
{isUserLoggedIn && userRole === UserRole.WRITE &&
<li><a onClick={() => onOpenClosePilotForm(FormMode.EDIT, info.row.original.id)}><FontAwesomeIcon icon={faPen} />Edit</a></li>
}
<li><a onClick={() => onOpenClosePilotForm(FormMode.VIEW, info.row.original.id)}><FontAwesomeIcon icon={faEye} />View</a></li>
{isUserLoggedIn && userRole === UserRole.WRITE &&
<li><a onClick={() => onDeletePilot(info.row.original.id)}><FontAwesomeIcon icon={faTrash} />Delete</a></li>
}
</ul>
</div>
)
}
} }
] ]
const textAlignment = { const renderCell = (pilot: any, columnKey: any) => {
center: 'text-center', const cellValue = pilot[columnKey]
left: 'text-start',
right: 'text-end'
};
const table = useReactTable({ switch (columnKey) {
data: state.pilots, case 'actions': {
columns: columns, return (
getCoreRowModel: getCoreRowModel(), <Dropdown>
getPaginationRowModel: getPaginationRowModel() <DropdownTrigger>
}); <Button isIconOnly variant='light' size='lg'>
<FontAwesomeIcon icon={faEllipsisVertical} />
</Button>
</DropdownTrigger>
<DropdownMenu>
<DropdownSection showDivider>
<DropdownItem
key='edit'
onPress={() => onOpenClosePilotForm(FormMode.EDIT, pilot.id)}
startContent={<FontAwesomeIcon icon={faPen} />}
>
Edit
</DropdownItem>
<DropdownItem
key='view'
onPress={() => onOpenClosePilotForm(FormMode.VIEW, pilot.id)}
startContent={<FontAwesomeIcon icon={faEye} />}
>
View
</DropdownItem>
</DropdownSection>
<DropdownSection>
<DropdownItem
key='Delete'
onPress={() => onDeletePilot(pilot.id)}
startContent={<FontAwesomeIcon icon={faTrash} />}
>
Delete
</DropdownItem>
</DropdownSection>
</DropdownMenu>
</Dropdown>
)
}
default: {
return cellValue
}
}
}
useEffect(() => { useEffect(() => {
if (!state.isFormOpen) { if (!state.isFormOpen) {
@@ -180,85 +188,52 @@ const Pilots: React.FC<unknown> = () => {
</div> </div>
<div className='col-span-2 justify-self-end self-center'> <div className='col-span-2 justify-self-end self-center'>
{userRole === UserRole.WRITE && {userRole === UserRole.WRITE &&
<button <Button
className='btn btn-primary' color='primary'
onClick={() => onOpenClosePilotForm(FormMode.ADD)} onPress={() => onOpenClosePilotForm(FormMode.ADD)}
startContent={<FontAwesomeIcon icon={faPlus} />}
data-testid="pilot-add-button" data-testid="pilot-add-button"
> >
<FontAwesomeIcon icon={faPlus} />
Add Pilot Add Pilot
</button> </Button>
} }
</div> </div>
{!state.isLoading && state.alert && ( {!state.isLoading && state.alert && (
<div className='col-span-12'> <div className='col-span-12'>
<Alert <Alert
className='mb-5'
onClose={() => onClose={() =>
dispatch({ type: 'SET_ALERT', payload: undefined }) dispatch({ type: 'SET_ALERT', payload: undefined })
} }
severity={state.alert.severity} color={state.alert.severity}
> title={state.alert.message}
{state.alert.message} />
</Alert>
</div> </div>
)} )}
<div className='col-span-12 bg-base-100 p-5 border border-base-100 rounded-lg'> <div className='col-span-12'>
{state.pilots.length > 0 && screenSize !== ScreenSize.SM && {state.pilots.length > 0 && screenSize !== ScreenSize.SM &&
<table className='table min-w-full h-auto table-auto w-full'> <Table>
<thead className='[&>tr]:first:rounded-lg bg-base-200'> <TableHeader columns={columns}>
{table.getHeaderGroups().map((headerGroup) => ( {(column) => (
<tr className='group/tr outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2' key={headerGroup.id}> <TableColumn
{headerGroup.headers.map((header) => { key={column.id}
return ( align={column.id === "actions" ? "center" : "start"}
<th >
className={`${header.column.columnDef.meta?.headerAlign ? header.column.columnDef.meta?.headerAlign : ''} group/th px-3 h-10 align-middle bg-default-100 whitespace-nowrap text-foreground-500 text-tiny font-semibold rounded data-[sortable=true]:cursor-pointer data-[hover=true]:text-foreground-400 outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2 text-start`} {column.name}
colSpan={header.colSpan} </TableColumn>
key={header.id} )}
> </TableHeader>
{header.isPlaceholder ? null : ( <TableBody items={state.pilots}>
<div> {(item) => (
{flexRender( <TableRow key={item.id}>
header.column.columnDef.header, {(columnKey => (
header.getContext() <TableCell>
)} {renderCell(item, columnKey)}
{/* {header.column.getCanFilter() ? ( </TableCell>
<div> ))}
<Filter column={header.column} table={table} /> </TableRow>
</div> )}
) : null} */} </TableBody>
</div> </Table>
)}
</th>
);
})}
</tr>
))}
</thead>
<tbody>
<>
{table.getRowModel().rows.map((row) => {
return (
<tr className='group/tr outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2' key={row.id}>
{row.getVisibleCells().map((cell) => {
return (
<td
className={`${cell.column.columnDef.meta?.align ? cell.column.columnDef.meta?.align : ''} py-2 px-3 relative align-middle whitespace-normal text-small font-normal [&>*]:z-1 [&>*]:relative outline-solid outline-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-focus data-[focus-visible=true]:outline-offset-2 before:pointer-events-none before:content-[''] before:absolute before:z-0 before:inset-0 before:opacity-0 data-[selected=true]:before:opacity-100 group-data-[disabled=true]/tr:text-foreground-300 group-data-[disabled=true]/tr:cursor-not-allowed before:bg-default/60 data-[selected=true]:text-default-foreground first:before:rounded-s-lg last:before:rounded-e-lg text-start`}
key={cell.id}
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</td>
);
})}
</tr>
);
})}
</>
</tbody>
</table>
} }
{state.pilots.length > 0 && screenSize === ScreenSize.SM && {state.pilots.length > 0 && screenSize === ScreenSize.SM &&
<PilotCard pilots={state.pilots} onDelete={onDeletePilot} onOpenCloseForm={onOpenClosePilotForm} /> <PilotCard pilots={state.pilots} onDelete={onDeletePilot} onOpenCloseForm={onOpenClosePilotForm} />

View File

@@ -3,18 +3,17 @@ import { useAppContext } from '../../hooks/appContext/UseAppContext';
import { AxiosResponse } from 'axios'; import { AxiosResponse } from 'axios';
import { User } from '@microsoft/microsoft-graph-types'; import { User } from '@microsoft/microsoft-graph-types';
import { useOidc } from '../../auth/oidcConfig'; import { useOidc } from '../../auth/oidcConfig';
import { Avatar, Button, Link, Navbar, NavbarBrand, NavbarContent, NavbarItem, DropdownTrigger, DropdownMenu, DropdownItem, Dropdown } from '@heroui/react';
import httpClient from '../../httpClient/httpClient' import httpClient from '../../httpClient/httpClient'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBars, faPlane, faSignIn, faSignOut } from '@fortawesome/free-solid-svg-icons' import { faPlane, faSignIn, faSignOut } from '@fortawesome/free-solid-svg-icons'
import { NavLink, useLocation } from 'react-router-dom'; import { useLocation } from 'react-router-dom';
import { useBreakpoints } from '../../hooks/useBreakpoints/UseBreakpoints';
import { ScreenSize } from '../../enums/screenSize';
const SiteNav = () => { const SiteNav = () => {
const [userPhoto, setUserPhoto] = useState<string>(); const [userPhoto, setUserPhoto] = useState<string>();
const appContext = useAppContext(); const appContext = useAppContext();
const { screenSize } = useBreakpoints();
const { isUserLoggedIn, logout, login } = useOidc() const { isUserLoggedIn, logout, login } = useOidc()
const { pathname } = useLocation()
const pages = [ const pages = [
{ {
name: 'Flights', name: 'Flights',
@@ -54,39 +53,13 @@ const SiteNav = () => {
} }
}; };
const Brand = () => {
return (
<>
<img
className='mr-1'
height={35}
width={35}
src='noahspan-logo.png'
/>
<FontAwesomeIcon className='mt-1' icon={faPlane} size='2x' />
</>
)
}
const Links = () => {
return (
<>
{pages.map((page) => {
return (
<li><NavLink to={page.path}>{page.name}</NavLink></li>
)
})}
</>
)
}
useEffect(() => { useEffect(() => {
const setUserProfile = async () => { const setUserProfile = async () => {
try { try {
const userProfile = await getUserProfile(); const userProfile = await getUserProfile();
// const userPhoto = await getUserPhoto(); const userPhoto = await getUserPhoto();
// setUserPhoto(userPhoto); setUserPhoto(userPhoto);
appContext.dispatch({ appContext.dispatch({
type: 'SET_USER_PROFILE', type: 'SET_USER_PROFILE',
@@ -105,67 +78,54 @@ const SiteNav = () => {
} }
}, [isUserLoggedIn]); }, [isUserLoggedIn]);
useEffect(() => {
console.log(screenSize)
}, [screenSize])
return ( return (
<div className="navbar bg-base-100 shadow-sm w-full"> <Navbar isBordered maxWidth='full' position='static'>
<div className={`navbar-start ${screenSize !== ScreenSize.SM && screenSize !== ScreenSize.MD ? 'ml-8' : ''}`}> <NavbarContent>
{screenSize === ScreenSize.SM || screenSize === ScreenSize.MD ? ( <NavbarBrand>
<div className="dropdown"> <img
<div tabIndex={0} role="button" className="btn btn-ghost lg:hidden"> height={35}
<FontAwesomeIcon icon={faBars} size='xl' /> width={35}
</div> src='noahspan-logo.png'
<ul style={{ marginRight: '5px' }}
tabIndex={-1} />
className="menu menu-sm dropdown-content bg-base-100 rounded-box z-1 mt-3 w-52 p-2 shadow"> <FontAwesomeIcon icon={faPlane} size='2x' />
<Links /> </NavbarBrand>
</ul> </NavbarContent>
</div> <NavbarContent justify='center'>
) : ( {pages.length > 0 && pages.map((page, index) => {
<Brand /> return (
)} <NavbarItem isActive={pathname === page.path ? true : false} key={index}>
</div> <Link color={pathname === page.path ? 'primary' : 'foreground'} href={page.path}>
<div className="navbar-center"> {page.name}
<ul className="menu menu-horizontal px-1"> </Link>
{screenSize === ScreenSize.SM || screenSize === ScreenSize.MD ? ( </NavbarItem>
<Brand /> )
) : ( })}
<Links /> </NavbarContent>
)} <NavbarContent justify='end'>
</ul>
</div>
<div className={`navbar-end ${screenSize !== ScreenSize.SM && screenSize !== ScreenSize.MD ? 'ml-8' : ''}`}>
{!isUserLoggedIn && {!isUserLoggedIn &&
<button className='btn btn-ghost' onClick={() => login()}><FontAwesomeIcon icon={faSignIn} />Sign In</button> <Button
color='default'
onPress={() => login()}
startContent={<FontAwesomeIcon icon={faSignIn} />}
>
Sign In
</Button>
} }
{isUserLoggedIn && {isUserLoggedIn &&
<div className='dropdown dropdown-end'> <Dropdown>
<div tabIndex={0} role='button'> <DropdownTrigger>
<div className={`avatar ${userPhoto ? userPhoto : 'avatar-placeholder'}`}> <Avatar name={appContext.state.userProfile.displayName?.toString()} src={userPhoto}></Avatar>
{userPhoto && </DropdownTrigger>
<div className='w-12 rounded-full'> <DropdownMenu>
<img src={userPhoto} /> <DropdownItem key='signout' onPress={() => logout({redirectTo: 'specific url', url: '/'})} startContent={<FontAwesomeIcon icon={faSignOut} />}>
</div> Sign Out
} </DropdownItem>
{!userPhoto && </DropdownMenu>
<div className='bg-neutral text-neutral-content w-10 rounded-full'> </Dropdown>
<span>NS</span>
</div>
}
</div>
</div>
<ul
tabIndex={0}
className='dropdown-content menu bg-base-100 rounded-box z-1 w-52 p-2 shadow-sm border border-base-300'
>
<li><a onClick={() => logout({redirectTo: 'specific url', url: '/'})}><FontAwesomeIcon icon={faSignOut} />Sign Out</a></li>
</ul>
</div>
} }
</div> </NavbarContent>
</div> </Navbar>
); );
}; };

View File

@@ -0,0 +1,53 @@
#app {
height: 100%;
}
html,
body {
position: relative;
height: 100%;
}
body {
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: 0;
padding: 0;
}
.swiper {
width: 100%;
height: 100%;
}
.swiper-wrapper {
margin-bottom: 20px;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
display: flex;
justify-content: center;
align-items: center;
}
.swiper-slide img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.swiper-pagination-bullet {
background-color: #000000;
height: 13px;
width: 13px;
border: 2px solid #FFFFFF;
}
.swiper-pagination-bullet-active {
box-shadow: 0 0 0 1px #000000;
}

View File

@@ -4,6 +4,10 @@ import { AxiosInstance, AxiosResponse } from 'axios';
import { useAuth } from 'react-oidc-context' import { useAuth } from 'react-oidc-context'
import { MapContainer, TileLayer } from 'react-leaflet'; import { MapContainer, TileLayer } from 'react-leaflet';
import ReactLeafletKml from 'react-leaflet-kml'; import ReactLeafletKml from 'react-leaflet-kml';
import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css';
import './TrackMap.css';
import 'leaflet/dist/leaflet.css'; import 'leaflet/dist/leaflet.css';
import httpClient from '../../httpClient/httpClient' import httpClient from '../../httpClient/httpClient'
@@ -37,7 +41,7 @@ const TrackMap = ({ height, logId, tracks }: TrackMapProps) => {
center={[45.14489, -93.21019]} center={[45.14489, -93.21019]}
scrollWheelZoom={false} scrollWheelZoom={false}
style={{ height: height, width: '100%' }} style={{ height: height, width: '100%' }}
zoom={7} zoom={8}
> >
<Suspense> <Suspense>
<TileLayer <TileLayer

View File

@@ -7,6 +7,7 @@ import ConfirmationDialog from "../confirmationDialog/ConfirmationDialog";
import { initialState, reducer } from "./reducer"; import { initialState, reducer } from "./reducer";
import TrackMap from "../trackMap/TrackMap"; import TrackMap from "../trackMap/TrackMap";
import httpClient from "../../httpClient/httpClient"; import httpClient from "../../httpClient/httpClient";
import { Button, Input, Spinner } from '@heroui/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUpload, faTrash, faXmark } from '@fortawesome/free-solid-svg-icons'; import { faUpload, faTrash, faXmark } from '@fortawesome/free-solid-svg-icons';
import { useLogbookContext } from "../../hooks/logbookContext/UseLogbookContext"; import { useLogbookContext } from "../../hooks/logbookContext/UseLogbookContext";
@@ -27,7 +28,7 @@ const TracksForm = () => {
} catch (error) { } catch (error) {
const axiosError = error as AxiosError; const axiosError = error as AxiosError;
logbookContext.dispatch({ type: 'SET_FORM_ALERT', payload: { severity: 'error', message: axiosError.message }}) logbookContext.dispatch({ type: 'SET_FORM_ALERT', payload: { severity: 'danger', message: axiosError.message }})
} }
} }
@@ -107,6 +108,11 @@ const TracksForm = () => {
return ( return (
<div className='grid grid-cols-12 gap-3'> <div className='grid grid-cols-12 gap-3'>
{state.tracks.length > 0 &&
<div className="col-span-12">
<TrackMap height='400px' logId={logbookContext.state.selectedLogId!} tracks={state.tracks} />
</div>
}
<> <>
{state.tracks.length > 0 && state.tracks.map((track, index) => { {state.tracks.length > 0 && state.tracks.map((track, index) => {
const filename: string = track.url.substring(track.url.lastIndexOf('/') + 1); const filename: string = track.url.substring(track.url.lastIndexOf('/') + 1);
@@ -114,25 +120,26 @@ const TracksForm = () => {
return ( return (
<> <>
<div className='col-span-10'> <div className='col-span-10'>
<input className='input w-full' disabled={state.isDisabled} key={index} readOnly type='text' value={filename} /> <Input isDisabled={state.isDisabled} key={index} type='text' value={filename}/>
</div> </div>
<div className='col-span-2'> <div className='col-span-2'>
<button className='btn w-full' disabled={state.isDisabled} key={index} onClick={() => onDeleteTrack(track.id, filename, index)}><FontAwesomeIcon icon={faTrash} /></button> <Button isDisabled={state.isDisabled} key={index} isIconOnly onPress={() => onDeleteTrack(track.id, filename, index)}><FontAwesomeIcon icon={faTrash} /></Button>
</div> </div>
</> </>
) )
})} })}
{logbookContext.state.formMode === FormMode.ADD && <div className='col-span-12'>
<div className='col-span-12'> <Button
<label as='label'
className='btn cursor-pointer w-full' color='primary'
> isDisabled={state.isDisabled}
<FontAwesomeIcon icon={faUpload} /> fullWidth={true}
Upload Track startContent={<FontAwesomeIcon icon={faUpload} />}
<input className='hidden' id='track-upload' onChange={handleFileUpload} type='file' /> >
</label> Upload Track
</div> <input hidden onChange={handleFileUpload} type='file' />
} </Button>
</div>
{state.isConfirmDialogOpen && ( {state.isConfirmDialogOpen && (
<ConfirmationDialog <ConfirmationDialog
contentText="Are you sure you want to delete this track?" contentText="Are you sure you want to delete this track?"

View File

@@ -1,7 +1,7 @@
export enum ScreenSize { export enum ScreenSize {
SM = 'SM', SM,
MD = 'MD', MD,
LG = 'LG', LG,
XL = 'XL', XL,
XXL = 'XXL' XXL
} }

3
client/src/hero.ts Normal file
View File

@@ -0,0 +1,3 @@
// hero.ts
import { heroui } from "@heroui/react";
export default heroui();

View File

@@ -14,17 +14,17 @@ export const useBreakpoints = () => {
break; break;
} }
case width >= 640 && width < 1024: { case width >= 640: {
size = ScreenSize.MD; size = ScreenSize.MD;
break; break;
} }
case width >= 1024 && width < 1280: { case width >= 1024: {
size = ScreenSize.LG size = ScreenSize.LG
break; break;
} }
case width >= 1280 && width < 1536: { case width >= 1280: {
size = ScreenSize.XL; size = ScreenSize.XL;
break; break;

View File

@@ -15,7 +15,7 @@ httpClient.interceptors.request.use(async (config) => {
if (oidc.isUserLoggedIn) { if (oidc.isUserLoggedIn) {
const { accessToken } = await oidc.getTokens(); const { accessToken } = await oidc.getTokens();
console.log(accessToken)
config.headers.Authorization = `Bearer ${accessToken}`; config.headers.Authorization = `Bearer ${accessToken}`;
} }

View File

@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flying</title> <title>Flying</title>
</head> </head>
<body style="background-color: #f5f5f5;"> <body>
<div id="root"></div> <div id="root"></div>
</body> </body>
</html> </html>

View File

@@ -1,4 +1,4 @@
export interface Alert { export interface Alert {
severity: 'info' | 'error' | 'success' | 'warning'; severity: 'danger' | 'default' | 'success' | 'warning';
message: string; message: string;
} }

View File

@@ -1,42 +1,15 @@
@import "tailwindcss"; @import "tailwindcss";
@plugin "daisyui"; @plugin './hero.ts';
@plugin "daisyui/theme" { /* Note: You may need to change the path to fit your project structure */
name: "lofi"; @source '../../node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}';
default: true; @custom-variant dark (&:is(.dark *));
prefersdark: false;
color-scheme: "light";
--color-base-100: oklch(100% 0 0);
--color-base-200: oklch(97% 0 0);
--color-base-300: oklch(94% 0 0);
--color-base-content: oklch(0% 0 0);
--color-primary: oklch(15.906% 0 0);
--color-primary-content: oklch(100% 0 0);
--color-secondary: oklch(21.455% 0.001 17.278);
--color-secondary-content: oklch(100% 0 0);
--color-accent: oklch(26.861% 0 0);
--color-accent-content: oklch(100% 0 0);
--color-neutral: oklch(0% 0 0);
--color-neutral-content: oklch(100% 0 0);
--color-info: oklch(79.54% 0.103 205.9);
--color-info-content: oklch(15.908% 0.02 205.9);
--color-success: oklch(90.13% 0.153 164.14);
--color-success-content: oklch(18.026% 0.03 164.14);
--color-warning: oklch(88.37% 0.135 79.94);
--color-warning-content: oklch(17.674% 0.027 79.94);
--color-error: oklch(78.66% 0.15 28.47);
--color-error-content: oklch(15.732% 0.03 28.47);
--radius-selector: 0.5rem;
--radius-field: 0.5rem;
--radius-box: 0.5rem;
--size-selector: 0.25rem;
--size-field: 0.25rem;
--border: 1px;
--depth: 0;
--noise: 0;
}
@plugin "@tailwindcss/typography"; @plugin "@tailwindcss/typography";
body { @theme inline {
background-color: #f5f5f5; --color-primary: #000000;
min-height: 100vh; }
}

View File

@@ -3,9 +3,8 @@ import '@tanstack/react-table';
/* eslint-disable */ /* eslint-disable */
declare module '@tanstack/react-table' { declare module '@tanstack/react-table' {
interface ColumnMeta<TData extends RowData, TValue> { interface ColumnMeta<TData extends RowData, TValue> {
align?: 'text-left' | 'text-center' | 'text-right'; align?: 'left' | 'center' | 'right';
className?: string; headerAlign?: 'left' | 'center' | 'right';
headerAlign?: 'text-left' | 'text-center' | 'text-right';
} }
} }
/* eslint-enable */ /* eslint-enable */

View File

@@ -5,7 +5,6 @@ interface ImportMetaEnv {
readonly VITE_CLIENT_ID: string; readonly VITE_CLIENT_ID: string;
readonly VITE_ISSUER_URI: string; readonly VITE_ISSUER_URI: string;
readonly VITE_TENANT_ID: string; readonly VITE_TENANT_ID: string;
readonly VITE_USERINFO_ENDPOINT: string;
} }
interface ImportMeta { interface ImportMeta {

Binary file not shown.

View File

@@ -1,4 +1,4 @@
dbs: dbs:
- path: /mnt/data/flying.db - path: /var/lib/data/flying.db
replicas: replicas:
- path: /mnt/data/backup/flying.db - path: /mnt/backup/flying.db

View File

@@ -16,11 +16,11 @@ services:
container_name: restore container_name: restore
image: litestream/litestream:0.3.13 image: litestream/litestream:0.3.13
volumes: volumes:
- ./database/flying.db:/mnt/data/flying.db - ./database/flying.db:/var/lib/data/flying.db
- ./database/litestream/litestream.yml:/mnt/litestream/litestream.yml - ./database/litestream/litestream.yml:/mnt/litestream/litestream.yml
- backup:/mnt/data/backup - backup:/mnt/data/backup
- data:/mnt/data - data:/var/lib/data
command: restore -config /mnt/litestream/litestream.yml -if-db-not-exists -if-replica-exists /mnt/data/flying.db command: restore -config /mnt/litestream/litestream.yml -if-db-not-exists -if-replica-exists /var/lib/data/flying.db
app: app:
container_name: flying container_name: flying
@@ -31,9 +31,9 @@ services:
env_file: env_file:
- ./api/.env - ./api/.env
environment: environment:
- DB_PATH=../../mnt/data/flying.db - DB_PATH=../../var/lib/data/flying.db
volumes: volumes:
- data:/mnt/data - data:/var/lib/data
depends_on: depends_on:
restore: restore:
condition: service_completed_successfully condition: service_completed_successfully
@@ -44,7 +44,7 @@ services:
volumes: volumes:
- ./database/litestream/litestream.yml:/mnt/litestream/litestream.yml - ./database/litestream/litestream.yml:/mnt/litestream/litestream.yml
- backup:/mnt - backup:/mnt
- data:/mnt/data - data:/var/lib/data
command: replicate -config /mnt/litestream/litestream.yml command: replicate -config /mnt/litestream/litestream.yml
depends_on: depends_on:
app: app:

View File

@@ -1,3 +1,8 @@
# data "azuread_application" "app_registration" {
# provider = azuread.external_tenant
# display_name = module.environment.app_reg_name
# }
resource "azurerm_container_app" "container_app" { resource "azurerm_container_app" "container_app" {
name = module.environment.app_name name = module.environment.app_name
container_app_environment_id = data.azurerm_container_app_environment.container_app_environment.id container_app_environment_id = data.azurerm_container_app_environment.container_app_environment.id
@@ -9,7 +14,7 @@ resource "azurerm_container_app" "container_app" {
max_replicas = 2 max_replicas = 2
init_container { init_container {
args = ["restore", "-if-db-not-exists", "-if-replica-exists", "/mnt/data/flying.db"] args = ["restore", "-if-db-not-exists", "-if-replica-exists", "/var/lib/data/flying.db"]
cpu = 0.25 cpu = 0.25
image = "litestream/litestream:0.5.2" image = "litestream/litestream:0.5.2"
memory = "0.5Gi" memory = "0.5Gi"
@@ -17,13 +22,13 @@ resource "azurerm_container_app" "container_app" {
volume_mounts { volume_mounts {
name = "data" name = "data"
path = "/mnt/data" path = "/var/lib/data"
sub_path = "data"
} }
volume_mounts { volume_mounts {
name = "backup" name = "backup"
path = "/mnt/data/backup" path = "/mnt/data"
sub_path = "data"
} }
volume_mounts { volume_mounts {
@@ -42,13 +47,13 @@ resource "azurerm_container_app" "container_app" {
volume_mounts { volume_mounts {
name = "data" name = "data"
path = "/mnt/data" path = "/var/lib/data"
sub_path = "data"
} }
volume_mounts { volume_mounts {
name = "backup" name = "backup"
path = "/mnt/data/backup" path = "/mnt/data"
sub_path = "data"
} }
volume_mounts { volume_mounts {
@@ -60,7 +65,7 @@ resource "azurerm_container_app" "container_app" {
container { container {
cpu = 0.25 cpu = 0.25
image = "noahspan/flying:20586783321" image = "noahspan/flying:19615036250"
memory = "0.5Gi" memory = "0.5Gi"
name = "flying" name = "flying"
@@ -69,16 +74,6 @@ resource "azurerm_container_app" "container_app" {
secret_name = "azure-storage-connection-string" secret_name = "azure-storage-connection-string"
} }
env {
name = "AUTHORITY"
value = var.AUTHORITY
}
env {
name = "AUDIENCE"
value = var.CLIENT_ID
}
env { env {
name = "CLIENT_ID" name = "CLIENT_ID"
value = var.CLIENT_ID value = var.CLIENT_ID
@@ -89,21 +84,6 @@ resource "azurerm_container_app" "container_app" {
secret_name = "client-secret" secret_name = "client-secret"
} }
env {
name = "ISSUER_URL"
value = var.ISSUER_URL
}
env {
name = "JWKS_URI"
value = var.JWKS_URI
}
env {
name = "SESSION_SECRET"
secret_name = "session-secret"
}
env { env {
name = "TENANT_ID" name = "TENANT_ID"
value = var.EXTERNAL_TENANT_ID value = var.EXTERNAL_TENANT_ID
@@ -111,7 +91,7 @@ resource "azurerm_container_app" "container_app" {
env { env {
name = "DB_PATH" name = "DB_PATH"
value = "/mnt/data/flying.db" value = "/var/lib/data/flying.db"
} }
env { env {
@@ -130,8 +110,7 @@ resource "azurerm_container_app" "container_app" {
volume_mounts { volume_mounts {
name = "data" name = "data"
path = "/mnt/data" path = "/var/lib/data"
sub_path = "data"
} }
} }
@@ -180,11 +159,6 @@ resource "azurerm_container_app" "container_app" {
value = var.DOCKER_IO_PASSWORD value = var.DOCKER_IO_PASSWORD
} }
secret {
name = "session-secret"
value = var.SESSION_SECRET
}
lifecycle { lifecycle {
ignore_changes = [ template[0].container[0].image, template[0].container[0].image, template[0].init_container[0].image, registry[0].server ] ignore_changes = [ template[0].container[0].image, template[0].container[0].image, template[0].init_container[0].image, registry[0].server ]
} }

View File

@@ -1,6 +1,3 @@
variable "AUTHORITY" {
type = string
}
variable "CLIENT_ID" { variable "CLIENT_ID" {
type = string type = string
@@ -20,14 +17,6 @@ variable "DOCKER_IO_USERNAME" {
type = string type = string
} }
variable "ISSUER_URL" {
type = string
}
variable "JWKS_URI" {
type = string
}
variable "RESOURCE_GROUP_NAME" { variable "RESOURCE_GROUP_NAME" {
type = string type = string
} }
@@ -36,11 +25,6 @@ variable "EXTERNAL_TENANT_ID" {
type = string type = string
} }
variable "SESSION_SECRET" {
sensitive = true
type = string
}
variable "TENANT_ID" { variable "TENANT_ID" {
type = string type = string
} }

3078
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -14,7 +14,6 @@
"devDependencies": { "devDependencies": {
"@typescript-eslint/eslint-plugin": "^7.2.0", "@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0", "@typescript-eslint/parser": "^7.2.0",
"daisyui": "^5.5.5",
"eslint": "^8.42.0", "eslint": "^8.42.0",
"eslint-config-prettier": "^9.0.0", "eslint-config-prettier": "^9.0.0",
"eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-hooks": "^4.6.0",