Skip to content

Commit

Permalink
Issue 200 schema refinements (#214)
Browse files Browse the repository at this point in the history
* RepairRequestId to INT

* removed organisation table

* Removed Brands

* migration + removed OID

* modified test+endpoints to Number for repair request ID

* FrontEndTest

* fixed type errors + format

* type check fix

* used coerce

* removed brand file

---------

Co-authored-by: SetroZ <=>
Co-authored-by: Dylan To <[email protected]>
  • Loading branch information
SetroZ and dct0 authored Apr 29, 2024
1 parent 6cefe91 commit c6c5453
Show file tree
Hide file tree
Showing 24 changed files with 109 additions and 188 deletions.
38 changes: 38 additions & 0 deletions prisma/migrations/20240210012417_issue_200/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
Warnings:
- The primary key for the `RepairRequest` table will be changed. If it partially fails, the table could be left without primary key constraint.
- The `id` column on the `RepairRequest` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- You are about to drop the column `organisationId` on the `Staff` table. All the data in the column will be lost.
- You are about to drop the `Brand` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `Organisation` table. If the table is not empty, all the data it contains will be lost.
- Changed the type of `repairRequestId` on the `RepairRequestImage` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
*/
-- DropForeignKey
ALTER TABLE "RepairRequestImage" DROP CONSTRAINT "RepairRequestImage_repairRequestId_fkey";

-- DropForeignKey
ALTER TABLE "Staff" DROP CONSTRAINT "Staff_organisationId_fkey";

-- AlterTable
ALTER TABLE "RepairRequest" DROP CONSTRAINT "RepairRequest_pkey",
DROP COLUMN "id",
ADD COLUMN "id" SERIAL NOT NULL,
ADD CONSTRAINT "RepairRequest_pkey" PRIMARY KEY ("id");

-- AlterTable
ALTER TABLE "RepairRequestImage" DROP COLUMN "repairRequestId",
ADD COLUMN "repairRequestId" INTEGER NOT NULL;

-- AlterTable
ALTER TABLE "Staff" DROP COLUMN "organisationId";

-- DropTable
DROP TABLE "Brand";

-- DropTable
DROP TABLE "Organisation";

-- AddForeignKey
ALTER TABLE "RepairRequestImage" ADD CONSTRAINT "RepairRequestImage_repairRequestId_fkey" FOREIGN KEY ("repairRequestId") REFERENCES "RepairRequest"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
24 changes: 6 additions & 18 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ enum UserRole {
}

model RepairRequest {
id String @id @default(uuid())
id Int @id @default(autoincrement())
createdBy String //User id
assignedTo String @default("") //volunteer id
assignedTo String @default("") //volugit adnteer id
event Event @relation(fields: [eventId], references: [id]) //relation field (many repair_requests to one event)
eventId String
Expand Down Expand Up @@ -89,16 +89,12 @@ model ItemType {
events Event[]
}

model Brand {
name String @id
}

model RepairRequestImage {
id String @id @default(uuid())
s3Key String //Potentially to be changed for privacy reasons
repairRequest RepairRequest @relation(fields: [repairRequestId], references: [id])
repairRequestId String
repairRequestId Int
}

model EventImage {
Expand All @@ -118,16 +114,8 @@ model EventRepairer {
@@unique([userId, eventId])
}

model Organisation {
id String @id @default(uuid())
name String @unique
Roles Staff[]
}

model Staff {
id String @id @default(uuid())
clerkId String
role UserRole
org Organisation @relation(fields: [organisationId], references: [id])
organisationId String
id String @id @default(uuid())
clerkId String
role UserRole
}
15 changes: 6 additions & 9 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
/* eslint-disable no-console */
import { faker } from "@faker-js/faker";
import {
Brand,
Event,
EventRepairer,
ItemType,
Expand Down Expand Up @@ -46,14 +45,12 @@ async function createItemTypes(itemTypeNames: string[]) {
}

async function createBrands(brandNames: string[]) {
const brands: Brand[] = [];
const brands: string[] = [];

for (const name of brandNames) {
const brand = await prisma.brand.create({
data: { name }
});
const brand = name;

brands.push(brand);
brands.push(name);
console.log(brand);
}

Expand Down Expand Up @@ -97,7 +94,7 @@ async function createRandomRepairRequests(
count: number,
events: Event[],
itemTypes: ItemType[],
brands: Brand[]
brands: string[]
) {
const repairRequests: RepairRequest[] = [];

Expand All @@ -112,7 +109,7 @@ async function createRandomRepairRequests(
status: "PENDING",
description: faker.lorem.sentence(),
comment: faker.lorem.sentence(),
itemBrand: faker.helpers.arrayElement(brands).name,
itemBrand: faker.helpers.arrayElement(brands),
itemMaterial: faker.word.noun(),
requestDate: faker.date.past(),
updatedAt: faker.date.recent(),
Expand Down Expand Up @@ -169,7 +166,7 @@ async function main() {
faker.seed(fakerSeed);
await deleteAllData();
const itemTypes: ItemType[] = await createItemTypes(itemTypeNames);
const brands: Brand[] = await createBrands(brandNames);
const brands: string[] = await createBrands(brandNames);
const events: Event[] = await createRandomEvents(eventCount, itemTypes);
// const repairRequests: RepairRequest[] =
await createRandomRepairRequests(
Expand Down
2 changes: 1 addition & 1 deletion src/components/EventBox/request-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { User } from "@/types";

// Contains type of info stored in our event box.
type RequestProps = {
repairRequestId: string;
repairRequestId: number;
createdBy: User;
requestDate: string;
itemType: string;
Expand Down
13 changes: 3 additions & 10 deletions src/components/Forms/create-repair-request.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import FieldImageUpload from "@/components/FormFields/field-image-upload";
import SingleSelect from "@/components/FormFields/field-single-select";
import FieldTextArea from "@/components/FormFields/field-text-area";
import { TermsAndConditions } from "@/components/terms-and-conditions";
import { Brand, useBrands } from "@/hooks/brands";
import { EventOption, useEventOptions } from "@/hooks/events";
import { ItemType, useItemTypes } from "@/hooks/item-types";
import { useCreateRepairRequest } from "@/hooks/repair-request";
Expand All @@ -17,6 +16,8 @@ import uploadImage from "@/lib/upload-image";
import { createRepairRequestSchema } from "@/schema/repair-request";
import { CreateRepairRequest } from "@/types";

import FieldInput from "../FormFields/field-input";

export interface FormValues extends CreateRepairRequest {
tncAccepted: boolean;
}
Expand All @@ -42,7 +43,6 @@ export default function RepairRequestForm({ eventId }: { eventId?: string }) {
});

const { data: itemTypeList } = useItemTypes();
const { data: brandList } = useBrands();
const { data: eventOptions } = useEventOptions();
const { mutateAsync: createRepairRequest } = useCreateRepairRequest();
const router = useRouter();
Expand All @@ -67,19 +67,12 @@ export default function RepairRequestForm({ eventId }: { eventId?: string }) {
return (
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
{/* Input field for Brand of Item */}
<SingleSelect
<FieldInput
name="itemBrand"
control={control}
placeholder="Select a brand"
label="Brand"
rules={{ required: true }}
options={
brandList
? brandList.map((brand: Brand) => {
return { id: brand.name, text: brand.name };
})
: []
}
/>
<SingleSelect
name="itemType"
Expand Down
12 changes: 2 additions & 10 deletions src/components/Forms/prepopulated-repair-request-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import FieldInput from "@/components/FormFields/field-input";
import FieldRadio from "@/components/FormFields/field-radio";
import FieldSingleSelect from "@/components/FormFields/field-single-select";
import FieldTextArea from "@/components/FormFields/field-text-area";
import { Brand, useBrands } from "@/hooks/brands";
import { ItemType, useItemTypes } from "@/hooks/item-types";
import { updateRepairRequestSchema } from "@/schema/repair-request";
import type { GeneralRepairAttempt, RepairRequestResponse } from "@/types";
Expand All @@ -19,7 +18,6 @@ export default function PrepopulatedRepairAttemptForm({
onSubmit: SubmitHandler<GeneralRepairAttempt>;
}) {
const { data: itemTypes } = useItemTypes();
const { data: itemBrands } = useBrands();

let status;
switch (props.status) {
Expand Down Expand Up @@ -70,18 +68,12 @@ export default function PrepopulatedRepairAttemptForm({
/>

{/* Brand, Material */}
<FieldSingleSelect
<FieldInput
name="itemBrand"
label="Brand"
control={control}
rules={{ required: true }}
options={
itemBrands
? itemBrands.map((brand: Brand) => {
return { id: brand.name, text: brand.name };
})
: []
}
placeholder=""
/>
<FieldInput
name="itemMaterial"
Expand Down
19 changes: 2 additions & 17 deletions src/components/Forms/repair-request-form.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { Brand, ItemType } from "@prisma/client";
import { ItemType } from "@prisma/client";
import { SubmitHandler, useForm } from "react-hook-form";

import Button from "@/components/Button";
Expand All @@ -11,11 +11,9 @@ import { updateRepairRequestSchema } from "@/schema/repair-request";
import type { GeneralRepairAttempt } from "@/types";

export default function RepairAttemptForm({
itemBrands,
itemTypes,
onSubmit
}: {
itemBrands?: Brand[];
itemTypes?: ItemType[];
onSubmit?: SubmitHandler<GeneralRepairAttempt>;
}) {
Expand All @@ -33,18 +31,6 @@ export default function RepairAttemptForm({
}
});

let actualItemBrands;
itemBrands
? (actualItemBrands = itemBrands.map((type) => ({
id: type.name,
text: type.name
})))
: (actualItemBrands = [
{ id: 0, text: "Alienware" },
{ id: 1, text: "Giant Bicycles" },
{ id: 2, text: "Seiko" }
]);

let actualItemTypes;
itemTypes
? (actualItemTypes = itemTypes.map((type) => ({
Expand Down Expand Up @@ -87,12 +73,11 @@ export default function RepairAttemptForm({
/>

{/* Brand, Material */}
<FieldSingleSelect
<FieldInput
name="itemBrand"
label="Brand"
control={control}
rules={{ required: true }}
options={actualItemBrands}
/>
<FieldInput
name="itemMaterial"
Expand Down
2 changes: 1 addition & 1 deletion src/email/emails/repair-request-email.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {

interface RepairRequestEmailProps {
customerName?: string;
requestId?: string;
requestId?: number;
date?: string;
itemName?: string;
issueDescription?: string;
Expand Down
21 changes: 0 additions & 21 deletions src/hooks/brands.ts

This file was deleted.

15 changes: 0 additions & 15 deletions src/pages/api/brand.ts

This file was deleted.

7 changes: 6 additions & 1 deletion src/pages/api/event/[id]/repair-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { getRepairRequestSchema } from "@/schema/repair-request";
import repairRequestService from "@/services/repairRequest";
import userService from "@/services/user";
import { RepairRequestResponse, SortDirection } from "@/types";
import { isNumber } from "@/utils";

export default apiHandler({
get: getRepairRequests
Expand Down Expand Up @@ -64,7 +65,11 @@ async function getRepairRequests(
// Need to pass undefined directly to the OR
OR: searchWord
? [
{ id: { contains: searchWord, mode: "insensitive" } },
{
id: {
equals: isNumber(searchWord) ? Number(searchWord) : undefined
}
},
{ description: { contains: searchWord, mode: "insensitive" } },
// Users
{ assignedTo: { in: userIdList } },
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/event/[id]/repairers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { HttpStatusCode } from "axios";
import { NextApiRequest, NextApiResponse } from "next";
import { ApiError } from "next/dist/server/api-utils";
import { HttpStatusCode } from "axios";
import { z } from "zod";

import apiHandler from "@/lib/api-handler";
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/repair-request/[id].ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default apiHandler({
});

async function updateRepairRequest(req: NextApiRequest, res: NextApiResponse) {
const repairRequestId = z.string().parse(req.query.id);
const repairRequestId = z.coerce.number().parse(req.query.id);
const parsedData = updateRepairRequestSchema.parse(req.body);

const {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/repair-request/images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ async function getImages(req: NextApiRequest, res: NextApiResponse) {
const repairRequestId = req.query.repairRequestId as string;

const repairRequestImages = await prisma.repairRequestImage.findMany({
where: { repairRequest: { id: repairRequestId } }
where: { repairRequest: { id: Number(repairRequestId) } }
});

return res.status(200).json(repairRequestImages);
Expand Down
4 changes: 2 additions & 2 deletions src/pages/api/repair-request/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getAuth } from "@clerk/nextjs/server";
import type { NextApiRequest, NextApiResponse } from "next";
import { getAuth } from "@clerk/nextjs/server";

import apiHandler from "@/lib/api-handler";
import prisma from "@/lib/prisma";
Expand All @@ -12,7 +12,7 @@ export default apiHandler({

async function createRepairRequest(
req: NextApiRequest,
res: NextApiResponse<{ id: string }>
res: NextApiResponse<{ id: number }>
) {
const parsedData = createRepairRequestSchema.parse(req.body);

Expand Down
Loading

0 comments on commit c6c5453

Please sign in to comment.