route file no longer uses enums

This commit is contained in:
IZZY 2025-05-19 13:00:10 +01:00
parent c407d26e8b
commit 3c31b2187b
2 changed files with 28 additions and 47 deletions

View File

@ -1,24 +1,8 @@
// Datasource configuration
datasource db { datasource db {
provider = "sqlserver" provider = "sqlserver"
url = env("DATABASE_URL") url = env("DATABASE_URL")
} }
// Enums for Request
enum RequestType {
NEW_USER
CHANGE_LEVEL
DELETE
}
enum RequestOutcome {
FULFILLED
REJECTED
IN_PROGRESS
CANCELLED
OTHER
}
// User model // User model
model User { model User {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
@ -26,20 +10,19 @@ model User {
name String name String
email String @unique email String @unique
passwordHash String passwordHash String
role String @default("GUEST") @db.VarChar(10) // ADMIN, SCIENTIST, GUEST role String @default("GUEST") @db.VarChar(10) // Allowed: ADMIN, SCIENTIST, GUEST
scientist Scientist? @relation scientist Scientist? @relation
purchasedArtefacts Artefact[] @relation("UserPurchasedArtefacts") purchasedArtefacts Artefact[] @relation("UserPurchasedArtefacts")
requests Request[] @relation("UserRequests") requests Request[] @relation("UserRequests")
} }
// Request model
model Request { model Request {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
createdAt DateTime @default(now()) createdAt DateTime @default(now())
requestType RequestType requestType String @db.VarChar(20) // Allowed: NEW_USER, CHANGE_LEVEL, DELETE
requestingUser User @relation("UserRequests", fields: [requestingUserId], references: [id]) requestingUser User @relation("UserRequests", fields: [requestingUserId], references: [id])
requestingUserId Int requestingUserId Int
outcome RequestOutcome @default(IN_PROGRESS) outcome String @default("IN_PROGRESS") @db.VarChar(20) // Allowed: FULFILLED, REJECTED, IN_PROGRESS, CANCELLED, OTHER
} }
// Scientist model // Scientist model
@ -58,7 +41,6 @@ model Scientist {
artefacts Artefact[] @relation("ScientistArtefactCreator") artefacts Artefact[] @relation("ScientistArtefactCreator")
} }
// Earthquake model
model Earthquake { model Earthquake {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@ -75,7 +57,6 @@ model Earthquake {
observatories Observatory[] @relation("EarthquakeObservatory") observatories Observatory[] @relation("EarthquakeObservatory")
} }
// Observatory model
model Observatory { model Observatory {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@ -92,13 +73,12 @@ model Observatory {
earthquakes Earthquake[] @relation("EarthquakeObservatory") earthquakes Earthquake[] @relation("EarthquakeObservatory")
} }
// Artefact model
model Artefact { model Artefact {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
type String @db.VarChar(50) // Lava, Tephra, Ash, Soil type String @db.VarChar(50) // Lava, Tephra, Ash, Soil
warehouseArea String // Examples: "ZoneA-Shelf1", "ZoneB-Rack2", "ZoneC-Bin3" warehouseArea String
description String description String
earthquakeId Int earthquakeId Int
earthquake Earthquake @relation(fields: [earthquakeId], references: [id]) earthquake Earthquake @relation(fields: [earthquakeId], references: [id])
@ -106,7 +86,7 @@ model Artefact {
creator Scientist? @relation("ScientistArtefactCreator", fields: [creatorId], references: [id], onDelete: NoAction, onUpdate: NoAction) creator Scientist? @relation("ScientistArtefactCreator", fields: [creatorId], references: [id], onDelete: NoAction, onUpdate: NoAction)
required Boolean @default(true) required Boolean @default(true)
dateAddedToShop DateTime? dateAddedToShop DateTime?
shopPrice Float? // In Euros shopPrice Float?
purchased Boolean @default(false) purchased Boolean @default(false)
purchasedById Int? purchasedById Int?
purchasedBy User? @relation("UserPurchasedArtefacts", fields: [purchasedById], references: [id], onDelete: NoAction, onUpdate: NoAction) purchasedBy User? @relation("UserPurchasedArtefacts", fields: [purchasedById], references: [id], onDelete: NoAction, onUpdate: NoAction)
@ -117,6 +97,6 @@ model Pallet {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
warehouseArea String // Examples: "ZoneA-Shelf1", "ZoneB-Rack2", "ZoneC-Bin3" warehouseArea String
palletNote String palletNote String
} }

View File

@ -1,60 +1,61 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { PrismaClient, RequestType, RequestOutcome } from "@prisma/client"; import { PrismaClient } from "@prisma/client";
import fs from "fs/promises"; import fs from "fs/promises";
import path from "path"; import path from "path";
import { parse } from "csv-parse/sync"; import { parse } from "csv-parse/sync";
// Path to CSV file
const csvFilePath = path.resolve(process.cwd(), "public/requests.csv"); const csvFilePath = path.resolve(process.cwd(), "public/requests.csv");
const prisma = new PrismaClient(); const prisma = new PrismaClient();
type RequestType = "NEW_USER" | "CHANGE_LEVEL" | "DELETE";
type RequestOutcome = "FULFILLED" | "REJECTED" | "IN_PROGRESS" | "CANCELLED" | "OTHER";
type CsvRow = { type CsvRow = {
RequestType: string; RequestType: string;
RequestingUserId: string; // User id as string in CSV RequestingUserId: string;
Outcome?: string; // optional; default is IN_PROGRESS if not supplied Outcome?: string;
}; };
// Valid enums for checking const validRequestTypes: RequestType[] = ["NEW_USER", "CHANGE_LEVEL", "DELETE"];
const validRequestTypes = Object.values(RequestType); const validOutcomes: RequestOutcome[] = [
const validOutcomes = Object.values(RequestOutcome); "FULFILLED",
"REJECTED",
"IN_PROGRESS",
"CANCELLED",
"OTHER",
];
function normalizeRequestType(type: string | undefined): RequestType { function normalizeRequestType(type: string | undefined): RequestType {
if (!type) return RequestType.NEW_USER; if (!type) return "NEW_USER";
const norm = type.trim().toUpperCase().replace(" ", "_"); const norm = type.trim().toUpperCase().replace(" ", "_");
return (validRequestTypes.includes(norm as any) ? norm : RequestType.NEW_USER) as RequestType; return (validRequestTypes.includes(norm as RequestType) ? norm : "NEW_USER") as RequestType;
} }
function normalizeOutcome(outcome: string | undefined): RequestOutcome { function normalizeOutcome(outcome: string | undefined): RequestOutcome {
if (!outcome) return RequestOutcome.IN_PROGRESS; if (!outcome) return "IN_PROGRESS";
const norm = outcome.trim().toUpperCase().replace(" ", "_"); const norm = outcome.trim().toUpperCase().replace(" ", "_");
return (validOutcomes.includes(norm as any) ? norm : RequestOutcome.IN_PROGRESS) as RequestOutcome; return (validOutcomes.includes(norm as RequestOutcome) ? norm : "IN_PROGRESS") as RequestOutcome;
} }
export async function POST() { export async function POST() {
try { try {
// 1. Read the CSV file
const fileContent = await fs.readFile(csvFilePath, "utf8"); const fileContent = await fs.readFile(csvFilePath, "utf8");
// 2. Parse the CSV
const records: CsvRow[] = parse(fileContent, { const records: CsvRow[] = parse(fileContent, {
columns: true, columns: true,
skip_empty_lines: true, skip_empty_lines: true,
}); });
// 3. Transform each record for Prisma
const requests = records.map(row => ({ const requests = records.map(row => ({
requestType: normalizeRequestType(row.RequestType), requestType: normalizeRequestType(row.RequestType),
requestingUserId: parseInt(row.RequestingUserId, 10), requestingUserId: parseInt(row.RequestingUserId, 10),
outcome: normalizeOutcome(row.Outcome), outcome: normalizeOutcome(row.Outcome),
})); }));
// (optional) Filter out rows missing requestingUserId
const filteredRequests = requests.filter(r => !isNaN(r.requestingUserId)); const filteredRequests = requests.filter(r => !isNaN(r.requestingUserId));
// 4. Bulk create requests in database
await prisma.request.createMany({ await prisma.request.createMany({
data: filteredRequests, data: filteredRequests,
skipDuplicates: true, // in case request id/user-id already exists skipDuplicates: true,
}); });
return NextResponse.json({ success: true, count: filteredRequests.length }); return NextResponse.json({ success: true, count: filteredRequests.length });