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

Dashboard complexity #11

Merged
merged 17 commits into from
Apr 20, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
Warnings:

- You are about to drop the `_equipmenttorequest` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `_facilitytorequest` table. If the table is not empty, all the data it contains will be lost.
- Added the required column `equipmentId` to the `Request` table without a default value. This is not possible if the table is not empty.
- Added the required column `facilityId` to the `Request` table without a default value. This is not possible if the table is not empty.

*/
-- DropForeignKey
ALTER TABLE `_equipmenttorequest` DROP FOREIGN KEY `_EquipmentToRequest_A_fkey`;

-- DropForeignKey
ALTER TABLE `_equipmenttorequest` DROP FOREIGN KEY `_EquipmentToRequest_B_fkey`;

-- DropForeignKey
ALTER TABLE `_facilitytorequest` DROP FOREIGN KEY `_FacilityToRequest_A_fkey`;

-- DropForeignKey
ALTER TABLE `_facilitytorequest` DROP FOREIGN KEY `_FacilityToRequest_B_fkey`;

-- AlterTable
ALTER TABLE `request` ADD COLUMN `equipmentId` INTEGER NOT NULL,
ADD COLUMN `facilityId` INTEGER NOT NULL;

-- DropTable
DROP TABLE `_equipmenttorequest`;

-- DropTable
DROP TABLE `_facilitytorequest`;

-- AddForeignKey
ALTER TABLE `Request` ADD CONSTRAINT `Request_facilityId_fkey` FOREIGN KEY (`facilityId`) REFERENCES `Facility`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `Request` ADD CONSTRAINT `Request_equipmentId_fkey` FOREIGN KEY (`equipmentId`) REFERENCES `Equipment`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE `request` MODIFY `description` TINYTEXT NOT NULL;
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-- DropForeignKey
ALTER TABLE `request` DROP FOREIGN KEY `Request_equipmentId_fkey`;

-- DropForeignKey
ALTER TABLE `request` DROP FOREIGN KEY `Request_facilityId_fkey`;

-- AlterTable
ALTER TABLE `request` MODIFY `equipmentId` INTEGER NULL,
MODIFY `facilityId` INTEGER NULL;

-- AddForeignKey
ALTER TABLE `Request` ADD CONSTRAINT `Request_facilityId_fkey` FOREIGN KEY (`facilityId`) REFERENCES `Facility`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `Request` ADD CONSTRAINT `Request_equipmentId_fkey` FOREIGN KEY (`equipmentId`) REFERENCES `Equipment`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
10 changes: 10 additions & 0 deletions prisma/migrations/20240419061409_request_status_json/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
Warnings:

- You are about to drop the column `isAllowed` on the `request` table. All the data in the column will be lost.
- Added the required column `requestStatus` to the `Request` table without a default value. This is not possible if the table is not empty.

*/
-- AlterTable
ALTER TABLE `request` DROP COLUMN `isAllowed`,
ADD COLUMN `requestStatus` JSON NOT NULL;
19 changes: 12 additions & 7 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -107,16 +107,21 @@ model Equipment {
}

model Request {
id Int @id @default(autoincrement())
description String
facilities Facility[] @relation(name: "FacilityToRequest")
equipments Equipment[] @relation(name: "EquipmentToRequest")
students Student[] @relation(name: "StudentToRequest")
isAllowed Boolean @default(false)
admins Admin[] @relation(name: "AdminToRequest")
id Int @id @default(autoincrement())
description String @db.TinyText
facility Facility? @relation(name: "FacilityToRequest", fields: [facilityId], references: [id])
equipment Equipment? @relation(name: "EquipmentToRequest", fields: [equipmentId], references: [id])
students Student[] @relation(name: "StudentToRequest")
admins Admin[] @relation(name: "AdminToRequest")

facilityId Int?
equipmentId Int?

/// [DatesType]
requestDates Json

/// [RequestStatusType]
requestStatus Json
}

enum UserRole {
Expand Down
6 changes: 4 additions & 2 deletions src/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ declare global {

namespace PrismaJson {
type DepartmentsType = { departments: Array<Department>?}
type DatesType = { dates: Array<Date>?}
type DatesType = { start: Date, end: Date }[]
type RequestStatusType = { adminId: number, requestStatus: "APPROVED" | "WAITING" | "REJECTED" }[]
}
}

type Departments = PrismaJson.DepartmentsType;
type Dates = PrismaJson.DatesType;
type RequestStatus = PrismaJson.RequestStatusType;

export { Departments, Dates };
export { Departments, Dates, RequestStatus };
12 changes: 12 additions & 0 deletions src/lib/components/search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { Page } from "@sveltejs/kit";

export const searchQuery = (searchTerm: string | undefined | null, category: string, page: Page<Record<string, string>, string | null>) => {
if (searchTerm === null || typeof searchTerm === "undefined") return {query: "", term: ""};
if (searchTerm.trim() === "") return {query: "", term: ""};

let query = new URLSearchParams(page.url.searchParams.toString());
query.set("term", searchTerm.trim());
query.set("cat", category);

return {query: query.toString() || "", term: searchTerm.trim()};
};
36 changes: 36 additions & 0 deletions src/routes/+error.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<script lang="ts">
import { page } from "$app/stores";

let statusMessage: string = "";

switch ($page.status) {
case 404:
statusMessage = "Sorry, the page you requested does not exist.";
break;
case 400:
statusMessage =
"Sorry, you may have made a bad request. Retype the URL or go back to the homepage.";
break;
case 401:
statusMessage = "Sorry, you are not authorized to view this page.";
break;
default:
statusMessage = $page.error?.message || "";
break;
}
</script>

<div class="grid grid-cols-3 grid-rows-4 h-screen text-center bg-red-100 overflow-hidden" style="grid-template-columns: 25% 50% 25%;">
<div
class="col-start-2 col-end-3 row-start-2 row-end-3 flex flex-col items-center justify-center"
>
<h1 class="text-9xl text-red-800 font-bold mb-2">{$page.status}</h1>
<p class="text-xl text-red-800 font-semibold mb-10">{statusMessage}</p>
</div>

<img
src="/error_leo.png"
class="col-start-2 col-end-3 row-start-3 row-end-5 self-end object-contain m-auto"
alt=""
/>
</div>
29 changes: 29 additions & 0 deletions src/routes/+layout.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { LayoutServerLoad } from './$types'
import { redirect, type Actions } from '@sveltejs/kit';
import { lucia } from '$lib/server/auth';
import db from '$lib/prisma';

export const load: LayoutServerLoad = async (event) => {
console.log(event.locals.user);

if (!event.locals.user) {
return { isLoggedIn: false }
}

const user = await db.user.findUnique({
select: { role: true, student: true, admin: true },
where: { id: event.locals.user.id }
})

if (user?.role == "STUDENT" && user?.student) {
return { isStudent: true }
}

if (!user?.admin && !user?.student) {
return { needsRegisterFollowup: true }
}

if (user?.role == "ADMIN" && user?.admin) {
return { isAdmin: true }
}
};
17 changes: 16 additions & 1 deletion src/routes/+layout.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
<script>
<script lang="ts">
import "../app.css";
import type { LayoutData } from "./$types";
import { page } from '$app/stores';
export let data: LayoutData;
</script>

{#if ($page.url.pathname === "/") || (data.isLoggedIn === false || data.needsRegisterFollowup === true)}
<div></div>
{:else if data.isStudent === true}
<a href="/dashboard">Dashboard</a>
<a href="/search">Search</a>
{:else if data.isAdmin === true}
<a href="/admindashboard">Dashboard</a>
<a href="/approvals">Approvals</a>
{/if}

<br>

<slot />
88 changes: 41 additions & 47 deletions src/routes/admindashboard/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { redirect } from "@sveltejs/kit";
import { error, redirect } from "@sveltejs/kit";
import type { Equipment, Facility, Student, User } from "@prisma/client";
import db from "$lib/prisma";
import type { PageServerLoad } from "./$types";
Expand All @@ -8,69 +8,63 @@ export const load: PageServerLoad = async (event) => {
redirect(302, "/login");
}

let returnInformation: {
userInfo: Omit<User, 'hashedPassword'>,
facilities: ({ admins: { user: Pick<User, 'id' | 'firstName' | 'lastName'> }[]; } & Omit<Facility, 'image'> & { image: string })[] | null,
equipments: ({ admins: { user: Pick<User, 'id' | 'firstName' | 'lastName'> }[]; } & Omit<Equipment, 'image'> & { image: string })[] | null
} = {
userInfo: { ...event.locals.user },
facilities: null,
equipments: null
}

const user = await db.user.findUnique({
select: { role: true, student: true, admin: true },
where: { id: event.locals.user.id }
})

if (user?.role == "STUDENT" && user?.student) {
redirect(302, "/dashboard");
throw error(401, "Unauthorized")
}

if (!user?.admin && !user?.student) {
redirect(302, "/register/next");
}

if (user?.role == "ADMIN" && user?.admin) {
const response = await db.admin.findUnique({
select: {
facilities: {
include: {
admins: {
select: {
user: { select: { firstName: true, lastName: true, id: true } }
}
if (!(user?.role == "ADMIN" || user?.admin)) {
throw error(401, "Unauthorized")
}

const response = await db.admin.findUnique({
select: {
facilities: {
include: {
admins: {
select: {
user: { select: { firstName: true, lastName: true, id: true } }
}
}
},
equipments: {
include: {
admins: {
select: {
user: { select: { firstName: true, lastName: true, id: true } }
}
}
},
equipments: {
include: {
admins: {
select: {
user: { select: { firstName: true, lastName: true, id: true } }
}
}
}
},
where: { userId: event.locals.user.id }
})
}
},
where: { userId: event.locals.user.id }
})

returnInformation.facilities = (response?.facilities.map(facility => {
const { image, ...otherProps } = facility;
return {
...otherProps,
image,
};
})) ?? null
returnInformation.equipments = (response?.equipments.map(equipment => {
const { image, ...otherProps } = equipment;
return {
...otherProps,
image,
};
})) ?? null
}
const requests = await db.request.findMany({
where: { admins: { some: { userId: event.locals.user.id } } },
select: {
id: true,
requestStatus: true,
facility: { select: { name: true, id: true, blockedDates: true } },
equipment: { select: { name: true, id: true, blockedDates: true } },
students: { include: { user: { select: { firstName: true, lastName: true, id: true } } } },
admins: { include: { user: { select: { firstName: true, lastName: true, id: true } } } }
}
})

return returnInformation;
return {
facilities: response?.facilities,
equipments: response?.equipments,
requests,
userInfo: { ...event.locals.user }
};
};
15 changes: 2 additions & 13 deletions src/routes/admindashboard/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<script lang="ts">
import type { PageData } from "./$types";

export let data: PageData;
</script>

Expand All @@ -25,13 +24,7 @@
.join(", ")}</td
>
<td>{facility.department}</td>
<td
><img
src={facility.image}
class="h-32"
alt={facility.name}
/></td
>
<td><img src={facility.image} class="h-32" alt={facility.name} /></td>
</tr>
{/each}
{/if}
Expand Down Expand Up @@ -61,11 +54,7 @@
>
<td>{equipment.department}</td>
<td
><img
src={equipment.image}
class="h-32"
alt={equipment.name}
/></td
><img src={equipment.image} class="h-32" alt={equipment.name} /></td
>
</tr>
{/each}
Expand Down
Loading
Loading