Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Show currently out equipment on front page #39

Merged
merged 3 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/components/CurrentlyOutEquipment.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import React from 'react';
import Skeleton from 'react-loading-skeleton';
import useSwr from 'swr';
import { getResponseContentOrError } from '../lib/utils';
import { CurrentlyOutEquipmentInfo } from '../models/misc/CurrentlyOutEquipmentInfo';
import { TableConfiguration, TableDisplay } from './TableDisplay';
import { Card } from 'react-bootstrap';
import TableStyleLink from './utils/TableStyleLink';

const EquipmentNameDisplayFn = (x: CurrentlyOutEquipmentInfo) =>
x.equipmentId ? <TableStyleLink href={'/equipment/' + x.equipmentId}>{x.name}</TableStyleLink> : <em>{x.name}</em>;

const CurrentlyOutEquipment: React.FC = () => {
const { data: currentlyOutEquipmentInfos } = useSwr('/api/equipment/currentlyOut', (url) =>
fetch(url).then((response) => getResponseContentOrError<CurrentlyOutEquipmentInfo[]>(response)),
);

if (!currentlyOutEquipmentInfos) {
return <Skeleton height={120}></Skeleton>;
}

const tableSettings: TableConfiguration<CurrentlyOutEquipmentInfo> = {
entityTypeDisplayName: 'utrustning',
defaultSortPropertyName: 'name',
defaultSortAscending: true,
hideTableFilter: true,
hideTableCountControls: true,
columns: [
{
key: 'name',
displayName: 'Utrustning',
getValue: (x: CurrentlyOutEquipmentInfo) => x.name,
getContentOverride: EquipmentNameDisplayFn,
textTruncation: true,
columnWidth: 300,
},
{
key: 'numberOfUnits',
displayName: 'Antal',
getValue: (x: CurrentlyOutEquipmentInfo) => x.numberOfUnits,
columnWidth: 220,
},
],
};

return (
<Card className="mb-3">
<Card.Header>Utlämnad utrustning</Card.Header>
<TableDisplay entities={currentlyOutEquipmentInfos} configuration={tableSettings} />
</Card>
);
};

export default CurrentlyOutEquipment;
29 changes: 29 additions & 0 deletions src/lib/db-access/equipmentList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import {
import { ensureDatabaseIsInitialized } from '../database';
import { validateEquipmentListEntryObjectionModel } from './equipmentListEntry';
import { compareLists, removeIdAndDates, withCreatedDate, withUpdatedDate } from './utils';
import { RentalStatus } from '../../models/enums/RentalStatus';
import { BookingType } from '../../models/enums/BookingType';
import { formatDatetimeForForm } from '../datetimeUtils';
import { Status } from '../../models/enums/Status';

export const fetchEquipmentList = async (
id: number,
Expand Down Expand Up @@ -41,6 +45,31 @@ export const fetchEquipmentListsForBooking = async (bookingId: number): Promise<
return EquipmentListObjectionModel.query().where('bookingId', bookingId).orderBy('id');
};

export const fetchOutEquipmentLists = async (): Promise<EquipmentListObjectionModel[]> => {
ensureDatabaseIsInitialized();
const now = formatDatetimeForForm(new Date());

return EquipmentListObjectionModel.query()
.join('Booking', 'Booking.id', '=', 'EquipmentList.bookingId')
.where({ rentalStatus: RentalStatus.OUT, bookingType: BookingType.RENTAL })
.orWhere((x) =>
x
.where({ bookingType: BookingType.GIG })
.where('equipmentOutDatetime', '<=', now)
.where('equipmentInDatetime', '>=', now)
.whereNot({status: Status.CANCELED})
)
.orWhere((x) =>
x
.where({ bookingType: BookingType.GIG })
.where('usageStartDatetime', '<=', now)
.where('usageEndDatetime', '>=', now)
.whereNot({status: Status.CANCELED})
)
.withGraphFetched('listEntries.equipment')
.withGraphFetched('listHeadings.listEntries.equipment');
};

export const updateEquipmentList = async (
id: number,
equipmentList: EquipmentListObjectionModel,
Expand Down
6 changes: 6 additions & 0 deletions src/models/misc/CurrentlyOutEquipmentInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface CurrentlyOutEquipmentInfo {
id: number;
equipmentId?: number;
name: string;
numberOfUnits: number;
}
52 changes: 52 additions & 0 deletions src/pages/api/equipment/currentlyOut.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { respondWithCustomErrorMessage, respondWithEntityNotFoundResponse } from '../../../lib/apiResponses';
import { withSessionContext } from '../../../lib/sessionContext';
import { fetchOutEquipmentLists } from '../../../lib/db-access/equipmentList';
import { groupBy, reduceSumFn } from '../../../lib/utils';
import { EquipmentListObjectionModel } from '../../../models/objection-models/BookingObjectionModel';

const handler = withSessionContext(async (req: NextApiRequest, res: NextApiResponse): Promise<Promise<void> | void> => {
switch (req.method) {
case 'GET':
await fetchOutEquipmentLists()
.then(getEquipmentFromLists)
.then((result) => res.status(200).json(result))
.catch((error) => respondWithCustomErrorMessage(res, error.message));

return;

default:
respondWithEntityNotFoundResponse(res);
}

return;
});

export default handler;

const getEquipmentFromLists = (equipmentLists: EquipmentListObjectionModel[]) => {
const listEntries = equipmentLists.flatMap((list) => [
...list.listEntries,
...list.listHeadings.flatMap((heading) => heading.listEntries),
]);

const equipmentGroupings = groupBy(
listEntries.filter((x) => x.equipmentId),
(x) => x.equipmentId?.toString() ?? '0',
);
const equipmentWithCount = Object.keys(equipmentGroupings).map((key) => {
const records = equipmentGroupings[key];
return {
equipmentId: key,
id: records[0].id,
name: records[0].equipment?.name,
numberOfUnits: records.map((x) => x.numberOfUnits).reduce(reduceSumFn, 0),
};
});

const customRows = listEntries
.filter((x) => !x.equipment)
.map((x) => ({ name: x.name, id: x.id, numberOfUnits: x.numberOfUnits }));

return [...equipmentWithCount, ...customRows];
};
2 changes: 2 additions & 0 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import Link from 'next/link';
import { IfNotReadonly } from '../components/utils/IfAdmin';
import TableStyleLink from '../components/utils/TableStyleLink';
import { KeyValue } from '../models/interfaces/KeyValue';
import CurrentlyOutEquipment from '../components/CurrentlyOutEquipment';

// eslint-disable-next-line react-hooks/rules-of-hooks
export const getServerSideProps = useUserWithDefaultAccessAndWithSettings();
Expand Down Expand Up @@ -74,6 +75,7 @@ const IndexPage: React.FC<Props> = ({ user: currentUser, globalSettings }: Props
bookings={outBookings}
showDateHeadings={false}
></TinyBookingTable>
<CurrentlyOutEquipment />
<Card className="mb-3">
<Card.Header className="d-flex">
<span className="flex-grow-1">Aktivitet</span>
Expand Down