Skip to content

Commit

Permalink
Merge pull request #102 from amosproj/develop
Browse files Browse the repository at this point in the history
connect backend and frontend context booking
  • Loading branch information
Faoilthiama authored Nov 30, 2022
2 parents b2d3a59 + 3fb532d commit 8fbdf55
Show file tree
Hide file tree
Showing 19 changed files with 372 additions and 118 deletions.
3 changes: 2 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"ms-vsliveshare.vsliveshare",
"esbenp.prettier-vscode",
"eamodio.gitlens",
"bradlc.vscode-tailwindcss"
"bradlc.vscode-tailwindcss",
"ms-vscode.vscode-typescript"
]
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public BookingController(ILogger<BookingController> logger, IBookingUsecases boo
/// Sample request:
/// Get /bookings/range?n=100&skip=50&direction=DESC&from=1669021730904&end=1669121730904 with JWT Token
/// </remarks>
///
///
/// <response code="200">Returns the booking list</response>
/// <response code="500">Internal Server Error</response>
/// <response code="400">Bad Request</response>
Expand Down Expand Up @@ -122,7 +122,7 @@ public IActionResult GetBookingsByDirection(int n = int.MaxValue, int skip = 0,
/// Sample request:
/// Get /bookings/recent with JWT Token
/// </remarks>
///
///
/// <response code="200">Returns the booking list</response>
/// <response code="404">User not found</response>
[HttpGet("recent")]
Expand All @@ -147,4 +147,4 @@ public IActionResult RecentBookings()
}
return NotFound();
}
}
}
13 changes: 13 additions & 0 deletions src/deskstar-frontend/components/BookingsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ const BookingsTable = ({
bookings,
onEdit,
onDelete,
onCheckIn,
}: {
bookings: IBooking[];
onEdit?: (booking: IBooking) => void;
onDelete?: Function;
onCheckIn?: Function;
}) => {
return (
<div className="overflow-x-auto">
Expand All @@ -24,6 +26,7 @@ const BookingsTable = ({
<th className="bg-deskstar-green-light text-center">End Time</th>
{onEdit && <th className="bg-deskstar-green-light"></th>}
{onDelete && <th className="bg-deskstar-green-light"></th>}
{onCheckIn && <th className="bg-deskstar-green-light"></th>}
</tr>
</thead>
<tbody>
Expand All @@ -33,6 +36,7 @@ const BookingsTable = ({
booking={booking}
onEdit={onEdit}
onDelete={onDelete}
onCheckIn={onCheckIn}
/>
))}
</tbody>
Expand All @@ -45,10 +49,12 @@ const BookingTableEntry = ({
booking,
onEdit,
onDelete,
onCheckIn,
}: {
booking: IBooking;
onEdit?: Function;
onDelete?: Function;
onCheckIn?: Function;
}) => {
const startDate = booking.startTime.split("T")[0];
const startTime = booking.startTime.split("T")[1].replace("Z", "");
Expand Down Expand Up @@ -78,6 +84,13 @@ const BookingTableEntry = ({
</button>
</td>
)}
{onCheckIn && (
<td className="text-right">
<button className="btn btn-ghost" onClick={() => onCheckIn(booking)}>
Check in
</button>
</td>
)}
</tr>
);
};
Expand Down
1 change: 0 additions & 1 deletion src/deskstar-frontend/components/DesksTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ const DesksTable = ({ desks }: { desks: IDesk[] }) => {
<table className="table table-zebra w-full">
<thead className="dark:text-black">
<tr>
{/* set size of Desk column */}
<th className="w-1/4 bg-deskstar-green-light text-left">Desk</th>
<th className="bg-deskstar-green-light text-left">Type</th>
<th className="bg-deskstar-green-light"></th>
Expand Down
35 changes: 17 additions & 18 deletions src/deskstar-frontend/components/RegisterPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useRouter } from "next/router";
import { useState } from "react";
import { useEffect, useState } from "react";
import { AuthResponse, register } from "../lib/api/AuthService";
import Input from "./forms/Input";

export default function RegisterPanel() {
Expand Down Expand Up @@ -28,27 +29,25 @@ export default function RegisterPanel() {
return;
}

const response = await fetch("http://localhost:3000/api/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
companyId: company,
firstName,
lastName,
mailAddress: email,
password,
}),
const response = await register({
companyId: company,
firstName,
lastName,
mailAddress: email,
password,
});

setClicked(false);

if (response.status !== 200) {
console.log(response.status);
const { error } = await response.json();

setError(error);
if (response !== AuthResponse.Success) {
switch (response) {
case AuthResponse.ErrorCompanyNotFound:
setError("Company not Found");
case AuthResponse.ErrorEmailaddressAlreadyExists:
setError("Email adress already registered");
default:
setError("unknown error");
}
return;
}

Expand Down
2 changes: 1 addition & 1 deletion src/deskstar-frontend/components/UserManagementWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function UserManagementWrapper({ children }: LayoutProps) {
<nav>
{navItems.map((item) => (
<Link
className="flex items-center text-lg mx-2 p-2 py-1 rounded cursor-pointer hover:bg-deskstar-green-light"
className="flex items-center text-lg mx-2 p-2 py-1 rounded cursor-pointer hover:bg-deskstar-green-light dark:hover:text-black"
href={item.href}
key={item.name}
>
Expand Down
21 changes: 16 additions & 5 deletions src/deskstar-frontend/components/UsersTable.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { IUser } from "../types/users";
import { FaTrashAlt, FaEdit, FaCheckCircle, FaTimesCircle } from "react-icons/fa";
import {
FaTrashAlt,
FaEdit,
FaCheckCircle,
FaTimesCircle,
} from "react-icons/fa";

export function UsersTable({
users,
Expand All @@ -17,7 +22,7 @@ export function UsersTable({
return (
<div className="overflow-x-auto">
<table className="table table-zebra w-full">
<thead>
<thead className="dark:text-black">
<tr>
<th className="bg-deskstar-green-light text-center">First Name</th>
<th className="bg-deskstar-green-light text-center">LastName</th>
Expand Down Expand Up @@ -81,11 +86,17 @@ const UsersTableEntry = ({
)}
{onApprovalUpdate && (
<td className="text-center">
<button className="btn btn-ghost" onClick={() => onApprovalUpdate(user, true)}>
<FaCheckCircle color="green"/>
<button
className="btn btn-ghost"
onClick={() => onApprovalUpdate(user, true)}
>
<FaCheckCircle color="green" />
</button>
<button className="btn btn-ghost">
<FaTimesCircle color="red" onClick={() => onApprovalUpdate(user, false)}/>
<FaTimesCircle
color="red"
onClick={() => onApprovalUpdate(user, false)}
/>
</button>
</td>
)}
Expand Down
2 changes: 1 addition & 1 deletion src/deskstar-frontend/components/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const userNavItems = [
},
{
name: "Add New Booking",
href: "/addBooking",
href: "/bookings/add",
},
];

Expand Down
65 changes: 65 additions & 0 deletions src/deskstar-frontend/lib/api/BookingService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { Session } from "next-auth";
import { IBooking } from "../../types/booking";
import { BACKEND_URL } from "./constants";

type QueryOptions = {
n?: number;
skip?: number;
direction?: "ASC" | "DESC";
start?: EpochTimeStamp;
end?: EpochTimeStamp;
};

function getParams(queryOptions: QueryOptions) {
const mapTable: [any, string][] = [
[queryOptions.n, "n"],
[queryOptions.skip, "skip"],
[queryOptions.direction, "direction"],
[queryOptions.start, "start"],
[queryOptions.end, "end"],
];

const params = new URLSearchParams();

mapTable.forEach((val) => {
if (val[0]) {
params.append(val[1], val[0]);
}
});

return params;
}

export async function getBookings(
session: Session,
queryOptions: QueryOptions
): Promise<IBooking[]> {
if (!session.user) return [];

const params = getParams(queryOptions);
const response = await fetch(BACKEND_URL + `/bookings/range?${params}`, {
headers: {
Authorization: `Bearer ${session.accessToken}`,
},
});

if (response.status !== 200) {
return [];
}

const data = await response.json();

const bookings: IBooking[] = data.map((val: any) => {
return {
bookingId: val.timestamp,
userId: session.user.id,
room: val.roomName,
floor: val.floorName,
building: val.buildingName,
location: "N/A",
...val,
};
});

return bookings;
}
6 changes: 3 additions & 3 deletions src/deskstar-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@
"react-icons": "^4.6.0"
},
"devDependencies": {
"@types/node": "18.11.8",
"@types/react": "18.0.24",
"@types/node": "^18.11.9",
"@types/react": "^18.0.25",
"@types/react-dom": "18.0.8",
"autoprefixer": "^10.4.13",
"eslint": "8.26.0",
"eslint-config-next": "13.0.0",
"postcss": "^8.4.18",
"tailwindcss": "^3.2.1",
"typescript": "4.8.4"
"typescript": "^4.9.3"
}
}
38 changes: 26 additions & 12 deletions src/deskstar-frontend/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import NextAuth from "next-auth";
import NextAuth, { Awaitable, NextAuthOptions, User } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { userAgent } from "next/server";
import { AuthResponse, authorize } from "../../../lib/api/AuthService";
import { Session } from "next-auth";

export const authOptions = {
export const authOptions: NextAuthOptions = {
secret: process.env.SECRET,
// Configure one or more authentication providers
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "E-Mailadresse", type: "text" },
password: { label: "Passwort", type: "password" },
},
async authorize(credentials, req) {
async authorize(credentials, req): Promise<User | null> {
// Check if credentials contains an email and password
if (!credentials || !credentials.email || !credentials.password) {
return null;
Expand All @@ -35,9 +35,9 @@ export const authOptions = {
company: "INTERFLEX",
name: "testuser",
email: "[email protected]",
isApproved : true,
isAdmin : true,
our_token: result as String,
isApproved: true,
isAdmin: true,
our_token: result as string,
};

if (user) {
Expand All @@ -50,11 +50,25 @@ export const authOptions = {
// ...add more providers here
],
callbacks: {
async session({ session }: {session: Session}) {
//TODO: refactor this if me route is available
// Send properties to the client, like if user is approved or is admin
session.user.isApproved = true;
session.user.isAdmin = true;
async jwt({ token, user, account, isNewUser }) {
if (user) {
if (user.our_token) {
token = { accessToken: user.our_token };
}
}
return token;
},
async session({ session, token }) {
session.accessToken = token.accessToken;

session.user = {
id: "1",
name: "testuser",
email: "[email protected]",
accessToken: token.accessToken,
isApproved: true,
isAdmin: true,
};

return session;
},
Expand Down
Loading

0 comments on commit 8fbdf55

Please sign in to comment.