Compare commits

...

9 Commits

12 changed files with 561 additions and 278 deletions

View File

@ -1,14 +1,11 @@
import bcryptjs from "bcryptjs";
import { validatePassword } from "@utils/validation";
import { SignJWT } from "jose";
import { NextResponse } from "next/server";
import { env } from "@utils/env";
import { prisma } from "@utils/prisma";
import { passwordStrengthCheck } from "@utils/validation";
// todo check email doesn't already exist
export async function POST(req: Request) {
try {
const { email, password, name } = await req.json();
@ -23,23 +20,11 @@ export async function POST(req: Request) {
return NextResponse.json({ message: "Sorry, this email is already in use" }, { status: 409 });
}
const passwordCheckResult = await passwordStrengthCheck(password);
const passwordCheckResult = validatePassword(password);
if ("message" in passwordCheckResult) {
return NextResponse.json({ message: passwordCheckResult.message }, { status: passwordCheckResult.status });
}
if (passwordCheckResult === "short") {
return NextResponse.json({ message: "Your password is shorter than 8 characters" }, { status: 400 });
} else if (passwordCheckResult === "long") {
return NextResponse.json({ message: "Your password is longer than 16 characters" }, { status: 400 });
} else if (passwordCheckResult === "no lower") {
return NextResponse.json({ message: "Your password must contain a lowercase letters" }, { status: 400 });
} else if (passwordCheckResult === "no upper") {
return NextResponse.json({ message: "Your password must contain a uppercase letters" }, { status: 400 });
} else if (passwordCheckResult === "no digit") {
return NextResponse.json({ message: "Your password must contain a number" }, { status: 400 });
} else if (passwordCheckResult === "no special") {
return NextResponse.json({ message: "Your password must contain a special character (!@#$%^&*)" }, { status: 400 });
} else if (passwordCheckResult === "end of function") {
return NextResponse.json({ message: "Password check script failure" }, { status: 500 });
} else {
try {
const newUser = await prisma.user.create({
data: {
@ -97,7 +82,6 @@ export async function POST(req: Request) {
console.error("Error creating user:", error);
return NextResponse.json({ message: "Internal Server Error" }, { status: 500 });
}
}
} catch (error) {
console.error("Error in signup endpoint:", error);
return NextResponse.json({ message: "Internal Server Error" }, { status: 500 });

View File

@ -5,7 +5,7 @@ import { env } from "@utils/env";
import { prisma } from "@utils/prisma";
import { apiAuthMiddleware } from "@utils/apiAuthMiddleware";
import { passwordStrengthCheck } from "@utils/validation";
import { validatePassword } from "@utils/validation";
export async function POST(req: Request) {
try {
@ -13,11 +13,22 @@ export async function POST(req: Request) {
if ("user" in authResult === false) return authResult;
const { user } = authResult;
const { userId, email, name, password, requestedRole } = await req.json();
const {
userId,
email,
name,
password,
requestedRole,
}: {
userId?: number;
email?: string;
name?: string;
password?: string;
requestedRole?: string;
} = await req.json();
// Trying to update a different user than themselves
// Only available to admins
// todo add senior scientists being able to update their juniors
if (userId && userId !== user.id) {
if (user.role !== "ADMIN") {
return NextResponse.json({ message: "Not authorised" }, { status: 401 });
@ -34,25 +45,12 @@ export async function POST(req: Request) {
}
}
// todo move to dedicated function
// Validate password strength if provided
let passwordHash = user.passwordHash;
if (password) {
const passwordCheckResult = await passwordStrengthCheck(password);
if (passwordCheckResult === "short") {
return NextResponse.json({ message: "Password is shorter than 8 characters" }, { status: 400 });
} else if (passwordCheckResult === "long") {
return NextResponse.json({ message: "Password is longer than 16 characters" }, { status: 400 });
} else if (passwordCheckResult === "no lower") {
return NextResponse.json({ message: "Password must contain lowercase letters" }, { status: 400 });
} else if (passwordCheckResult === "no upper") {
return NextResponse.json({ message: "Password must contain uppercase letters" }, { status: 400 });
} else if (passwordCheckResult === "no digit") {
return NextResponse.json({ message: "Password must contain a number" }, { status: 400 });
} else if (passwordCheckResult === "no special") {
return NextResponse.json({ message: "Password must contain a special character (!@#$%^&*)" }, { status: 400 });
} else if (passwordCheckResult === "end of function") {
return NextResponse.json({ message: "Password check script failure" }, { status: 500 });
const passwordCheckResult = validatePassword(password);
if ("message" in passwordCheckResult) {
return NextResponse.json({ message: passwordCheckResult.message }, { status: passwordCheckResult.status });
}
passwordHash = await bcryptjs.hash(password, 10);
}

View File

@ -0,0 +1,59 @@
import { NextResponse } from "next/server";
import { env } from "@utils/env";
import { prisma } from "@utils/prisma";
import { apiAuthMiddleware } from "@utils/apiAuthMiddleware";
export async function POST(req: Request) {
try {
const authResult = await apiAuthMiddleware();
if ("user" in authResult === false) return authResult;
const { user } = authResult;
const { userId }: { userId: number } = await req.json();
if (!userId) {
return NextResponse.json({ message: "User id required to delete" }, { status: 401 });
}
if (userId !== user.id && user.role !== "ADMIN") {
return NextResponse.json({ message: "Not authorised" }, { status: 401 });
}
await prisma.$transaction(async (tx) => {
// Handle Scientist and its subordinates
const scientist = await tx.scientist.findUnique({ where: { userId: userId } });
if (scientist) {
// Unlink subordinates
await tx.scientist.updateMany({
where: { superiorId: scientist.id },
data: { superiorId: null },
});
// Delete Scientist
await tx.scientist.delete({ where: { userId: userId } });
}
// Delete Requests
await tx.request.deleteMany({ where: { requestingUserId: userId } });
// Unlink Observatories (set creatorId to null)
await tx.observatory.updateMany({
where: { creatorId: userId },
data: { creatorId: null },
});
// Unlink Artefacts (set creatorId to null)
await tx.artefact.updateMany({
where: { creatorId: userId },
data: { creatorId: null },
});
// Delete User (Orders and Earthquakes are handled automatically)
await tx.user.delete({ where: { id: userId } });
});
return NextResponse.json({ message: "User deleted successfully" }, { status: 200 });
} catch (error) {
console.error("Error in delete-user endpoint:", error);
return NextResponse.json({ message: "Internal Server Error" }, { status: 500 });
}
}

View File

@ -0,0 +1,86 @@
import { NextRequest, NextResponse } from "next/server";
import { apiAuthMiddleware } from "@utils/apiAuthMiddleware";
import { prisma } from "@utils/prisma";
import { writeFile } from "fs/promises";
import { join } from "path";
export async function POST(request: NextRequest) {
try {
const formData = await request.formData();
const id = formData.get("id") as string;
const name = formData.get("name") as string | null;
const description = formData.get("description") as string | null;
const warehouseArea = formData.get("warehouseArea") as string | null;
const earthquakeCode = formData.get("earthquakeCode") as string | null;
const image = formData.get("image") as File | null;
const authResult = await apiAuthMiddleware();
if ("user" in authResult === false) return authResult;
const { user } = authResult;
if (!id) {
return NextResponse.json({ error: "Artefact ID required" }, { status: 400 });
}
const artefact = await prisma.artefact.findUnique({
where: { id: parseInt(id) },
});
if (!artefact) {
return NextResponse.json({ error: "Artefact not found" }, { status: 404 });
}
if (user.role !== "ADMIN" && user.role !== "SCIENTIST") {
return NextResponse.json({ error: "Not authorized" }, { status: 401 });
}
if (user.role === "SCIENTIST") {
const scientist = await prisma.scientist.findUnique({
where: {
userId: user.id,
},
include: {
subordinates: true,
},
});
if (!scientist || scientist.level !== "SENIOR") {
return NextResponse.json({ message: "Not authorised" }, { status: 401 });
}
}
let earthquakeId = artefact.earthquakeId;
if (earthquakeCode) {
const linkedEarthquake = await prisma.earthquake.findUnique({ where: { code: earthquakeCode } });
if (!linkedEarthquake) {
return NextResponse.json({ error: "Earthquake code not found" }, { status: 400 });
}
earthquakeId = linkedEarthquake.id;
}
let imageName = artefact.imageName;
if (image) {
const buffer = Buffer.from(await image.arrayBuffer());
const extension = image.type === "image/jpeg" ? "jpg" : "png";
imageName = `${name || artefact.name}-${new Date().toLocaleDateString("en-GB")}.${extension}`;
const imagePath = join(process.cwd(), "public", imageName);
await writeFile(imagePath, buffer);
}
const updatedArtefact = await prisma.artefact.update({
where: { id: parseInt(id) },
data: {
name: name || artefact.name,
description: description || artefact.description,
warehouseArea: warehouseArea || artefact.warehouseArea,
earthquakeId,
imageName,
},
});
return NextResponse.json({ message: "Artefact updated successfully", artefact: updatedArtefact }, { status: 200 });
} catch (e: any) {
return NextResponse.json({ error: e.message }, { status: 500 });
}
}

View File

@ -5,21 +5,40 @@ import { prisma } from "@utils/prisma";
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { palletNote, warehouseLocation } = body;
const { palletNote, warehouseArea } = body;
const authResult = await apiAuthMiddleware();
if ("user" in authResult === false) return authResult; // Handle error response
const { user } = authResult;
if (!palletNote || !warehouseLocation) {
if (user.role !== "ADMIN" && user.role !== "SCIENTIST") {
return NextResponse.json({ error: "Not authorized" }, { status: 401 });
}
if (user.role === "SCIENTIST") {
const scientist = await prisma.scientist.findUnique({
where: {
userId: user.id,
},
include: {
subordinates: true,
},
});
if (!scientist || scientist.level !== "SENIOR") {
return NextResponse.json({ message: "Not authorised" }, { status: 401 });
}
}
if (!palletNote || !warehouseArea) {
return NextResponse.json({ error: "Missing fields" }, { status: 400 });
}
await prisma.pallet.create({
data: {
palletNote,
warehouseArea: warehouseLocation,
warehouseArea,
},
});

View File

@ -1,35 +1,70 @@
import { NextRequest, NextResponse } from "next/server";
import { apiAuthMiddleware } from "@utils/apiAuthMiddleware";
import { prisma } from "@utils/prisma";
import { writeFile } from "fs/promises";
import { join } from "path";
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { name, type, description, location, earthquakeCode, warehouseLocation } = body;
const formData = await request.formData();
const name = formData.get("name") as string;
const type = formData.get("type") as string;
const description = formData.get("description") as string;
const earthquakeCode = formData.get("earthquakeCode") as string;
const warehouseArea = formData.get("warehouseArea") as string;
const image = formData.get("image") as File | null;
const authResult = await apiAuthMiddleware();
if ("user" in authResult === false) return authResult; // Handle error response
if ("user" in authResult === false) return authResult;
const { user } = authResult;
if (!name || !type || !description || !location || !earthquakeCode || !warehouseLocation) {
if (!name || !type || !description || !earthquakeCode || !warehouseArea) {
return NextResponse.json({ error: "Missing fields" }, { status: 400 });
}
if (user.role !== "ADMIN" && user.role !== "SCIENTIST") {
return NextResponse.json({ error: "Not authorized" }, { status: 401 });
}
if (user.role === "SCIENTIST") {
const scientist = await prisma.scientist.findUnique({
where: {
userId: user.id,
},
include: {
subordinates: true,
},
});
if (!scientist || scientist.level !== "SENIOR") {
return NextResponse.json({ message: "Not authorised" }, { status: 401 });
}
}
const linkedEarthquake = await prisma.earthquake.findUnique({ where: { code: earthquakeCode } });
if (!linkedEarthquake) {
return NextResponse.json({ error: "Earthquake code not found" }, { status: 400 });
}
let imageName = "NoImageFound.PNG";
if (image) {
const buffer = Buffer.from(await image.arrayBuffer());
const extension = image.type === "image/jpeg" ? "jpg" : "png";
imageName = `${name}-${new Date().toLocaleDateString("en-GB")}.${extension}`;
const imagePath = join(process.cwd(), "public", imageName);
await writeFile(imagePath, buffer);
}
await prisma.artefact.create({
data: {
name,
type,
description,
earthquakeId: linkedEarthquake.id,
warehouseArea: warehouseLocation,
imageName: "NoImageFound.PNG",
warehouseArea: warehouseArea,
imageName,
creatorId: user.id,
},
});

View File

@ -229,9 +229,8 @@ export default function Profile() {
}
setIsDeleting(true);
try {
// todo add delete user route
const res = await axios.post(
"/api/delete-user",
"/api/user/delete",
{ userId: user!.id },
{ headers: { "Content-Type": "application/json" } }
);

View File

@ -295,7 +295,6 @@ export default function Shop() {
"#" + Math.random().toString(24).substring(2, 10).toUpperCase() + new Date().toLocaleDateString("en-GB");
const orderNum = genOrder();
// todo add display of error
(async () => {
try {
const response = await axios.post("/api/shop/purchase", {
@ -309,8 +308,8 @@ export default function Shop() {
setShowThankYouModal(true);
setCart((c) => c.filter((a) => !artefactsToBuy.map((x) => x.id).includes(a.id)));
} catch (error) {
setError("Payment Failed");
console.error("Error posting artefacts:", error);
throw error;
}
})();
}

View File

@ -1,4 +1,5 @@
"use client";
import Image from "next/image";
import axios from "axios";
import useSWR from "swr";
import { Dispatch, SetStateAction, useMemo, useState } from "react";
@ -10,6 +11,12 @@ import { ExtendedArtefact } from "@appTypes/ApiTypes";
import { fetcher } from "@utils/axiosHelpers";
// Function to validate earthquake code format
const validateEarthquakeCode = (code: string): boolean => {
const pattern = /^E[A-Z]-[0-9]\.[0-9]-[A-Za-z]+-[0-9]{5}$/;
return pattern.test(code);
};
// Filter Component
function FilterInput({
value,
@ -33,8 +40,7 @@ function FilterInput({
>
<IoFilter
className={`cursor-pointer text-neutral-500 font-bold group-hover:text-blue-600
${!showSelectedFilter && value && "text-blue-600"}
`}
${!showSelectedFilter && value && "text-blue-600"}`}
/>
</div>
<div
@ -72,15 +78,10 @@ function FilterInput({
);
}
// Modal Component for Logging Artefact
function LogModal({ onClose }: { onClose: () => void }) {
const [name, setName] = useState("");
const [type, setType] = useState("");
const [description, setDescription] = useState("");
const [location, setLocation] = useState("");
const [earthquakeCode, setEarthquakeCode] = useState("");
const [warehouseLocation, setWarehouseLocation] = useState("");
const [isRequired, setIsRequired] = useState(true);
// Modal Component for Bulk Logging
function BulkLogModal({ onClose }: { onClose: () => void }) {
const [palletNote, setPalletNote] = useState("");
const [warehouseArea, setWarehouseArea] = useState("");
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
@ -90,25 +91,154 @@ function LogModal({ onClose }: { onClose: () => void }) {
}
};
// todo add uploading image
async function handleLog() {
if (!name || !type || !description || !location || !earthquakeCode || !warehouseLocation) {
if (!palletNote || !warehouseArea) {
setError("All fields are required.");
return;
}
setIsSubmitting(true);
try {
await axios.post("/api/warehouse/log", {
name,
type,
description,
location,
earthquakeCode,
warehouseLocation,
await axios.post("/api/warehouse/log-bulk", {
palletNote,
warehouseArea,
});
// todo replace with better alert
alert(`Logged ${name} to storage: ${warehouseLocation}`);
alert(`Logged bulk pallet to storage: ${warehouseArea}`);
onClose();
} catch {
setError("Failed to log pallet. Please try again.");
} finally {
setIsSubmitting(false);
}
}
return (
<div
className="fixed inset-0 bg-neutral-900 bg-opacity-50 flex justify-center items-center z-50"
onClick={handleOverlayClick}
>
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6 border border-neutral-300">
<h3 className="text-lg font-semibold mb-4 text-neutral-800">Log Bulk Pallet</h3>
{error && <p className="text-red-600 text-sm mb-2">{error}</p>}
<div className="space-y-2">
<textarea
placeholder="Pallet Delivery Note (e.g., 10 lava chunks, 5 ash samples)"
value={palletNote}
onChange={(e) => setPalletNote(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 h-24"
aria-label="Pallet Delivery Note"
disabled={isSubmitting}
/>
<input
type="text"
placeholder="Warehouse Area (e.g., B-05)"
value={warehouseArea}
onChange={(e) => setWarehouseArea(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Warehouse Area"
disabled={isSubmitting}
/>
</div>
<div className="flex justify-end gap-3 mt-4">
<button
onClick={onClose}
className="px-4 py-2 bg-neutral-200 text-neutral-800 rounded-md hover:bg-neutral-300 font-medium"
disabled={isSubmitting}
>
Cancel
</button>
<button
onClick={handleLog}
className={`px-4 py-2 bg-blue-600 text-white rounded-md font-medium flex items-center gap-2 ${
isSubmitting ? "opacity-50 cursor-not-allowed" : "hover:bg-blue-700"
}`}
disabled={isSubmitting}
>
{isSubmitting ? (
<>
<svg
className="animate-spin h-5 w-5 text-white"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
Logging...
</>
) : (
"Log Pallet"
)}
</button>
</div>
</div>
</div>
);
}
function LogModal({ onClose }: { onClose: () => void }) {
const [name, setName] = useState("");
const [type, setType] = useState("");
const [description, setDescription] = useState("");
const [earthquakeCode, setEarthquakeCode] = useState("");
const [warehouseArea, setWarehouseArea] = useState("");
const [isRequired, setIsRequired] = useState(true);
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [image, setImage] = useState<File | null>(null);
const handleOverlayClick = (e: { target: any; currentTarget: any }) => {
if (e.target === e.currentTarget) {
onClose();
}
};
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
const file = e.target.files[0];
if (file.size > 5 * 1024 * 1024) {
setError("Image size must be less than 5MB");
return;
}
if (!["image/jpeg", "image/png"].includes(file.type)) {
setError("Only JPEG or PNG images are allowed");
return;
}
setImage(file);
}
};
async function handleLog() {
if (!name || !type || !description || !earthquakeCode || !warehouseArea) {
setError("All fields are required.");
return;
}
if (!validateEarthquakeCode(earthquakeCode)) {
setError("Earthquake Code must be in format: EX-M.M-Country-##### (e.g., EC-3.9-Belgium-05467)");
return;
}
setIsSubmitting(true);
try {
const formData = new FormData();
formData.append("name", name);
formData.append("type", type);
formData.append("description", description);
formData.append("earthquakeCode", earthquakeCode);
formData.append("warehouseArea", warehouseArea);
if (image) {
formData.append("image", image);
}
await axios.post("/api/warehouse/log", formData, {
headers: { "Content-Type": "multipart/form-data" },
});
alert(`Logged ${name} to storage: ${warehouseArea}`);
onClose();
} catch {
setError("Failed to log artefact. Please try again.");
@ -126,6 +256,15 @@ function LogModal({ onClose }: { onClose: () => void }) {
<h3 className="text-lg font-semibold mb-4 text-neutral-800">Log New Artefact</h3>
{error && <p className="text-red-600 text-sm mb-2">{error}</p>}
<div className="space-y-2">
<input
type="file"
accept="image/jpeg,image/png"
onChange={handleImageChange}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Artefact Image"
disabled={isSubmitting}
/>
<input
type="text"
placeholder="Name"
@ -137,7 +276,7 @@ function LogModal({ onClose }: { onClose: () => void }) {
/>
<input
type="text"
placeholder="Type (e.g., Lava, Tephra, Ash"
placeholder="Type (e.g., Lava, Tephra, Ash)"
value={type}
onChange={(e) => setType(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
@ -154,18 +293,8 @@ function LogModal({ onClose }: { onClose: () => void }) {
/>
<input
type="text"
placeholder="Location"
value={location}
onChange={(e) => setLocation(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Artefact Location"
disabled={isSubmitting}
/>
<input
type="text"
placeholder="Earthquake Code"
placeholder="Earthquake Code (e.g., EC-3.9-Belgium-05467)"
value={earthquakeCode}
// todo check code is correct format
onChange={(e) => setEarthquakeCode(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Earthquake ID"
@ -173,11 +302,11 @@ function LogModal({ onClose }: { onClose: () => void }) {
/>
<input
type="text"
placeholder="Warehouse Location (e.g., A-12)"
value={warehouseLocation}
onChange={(e) => setWarehouseLocation(e.target.value)}
placeholder="Warehouse Area (e.g., A-12)"
value={warehouseArea}
onChange={(e) => setWarehouseArea(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Storage Location"
aria-label="Warehouse Area"
disabled={isSubmitting}
/>
<div className="flex items-center gap-2">
@ -234,137 +363,54 @@ function LogModal({ onClose }: { onClose: () => void }) {
);
}
// Modal Component for Bulk Logging
function BulkLogModal({ onClose }: { onClose: () => void }) {
const [palletNote, setPalletNote] = useState("");
const [warehouseLocation, setWarehouseLocation] = useState("");
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const handleOverlayClick = (e: { target: any; currentTarget: any }) => {
if (e.target === e.currentTarget) {
onClose();
}
};
async function handleLog() {
if (!palletNote || !warehouseLocation) {
setError("All fields are required.");
return;
}
setIsSubmitting(true);
try {
await axios.post("/api/warehouse/log-bulk", {
palletNote,
warehouseLocation,
});
// todo replace with better alert
alert(`Logged bulk pallet to storage: ${warehouseLocation}`);
onClose();
} catch {
setError("Failed to log pallet. Please try again.");
} finally {
setIsSubmitting(false);
}
}
return (
<div
className="fixed inset-0 bg-neutral-900 bg-opacity-50 flex justify-center items-center z-50"
onClick={handleOverlayClick}
>
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6 border border-neutral-300">
<h3 className="text-lg font-semibold mb-4 text-neutral-800">Log Bulk Pallet</h3>
{error && <p className="text-red-600 text-sm mb-2">{error}</p>}
<div className="space-y-2">
<textarea
placeholder="Pallet Delivery Note (e.g., 10 lava chunks, 5 ash samples)"
value={palletNote}
onChange={(e) => setPalletNote(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 h-24"
aria-label="Pallet Delivery Note"
disabled={isSubmitting}
/>
<input
type="text"
placeholder="Storage Location (e.g., B-05)"
value={warehouseLocation}
onChange={(e) => setWarehouseLocation(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Storage Location"
disabled={isSubmitting}
/>
</div>
<div className="flex justify-end gap-3 mt-4">
<button
onClick={onClose}
className="px-4 py-2 bg-neutral-200 text-neutral-800 rounded-md hover:bg-neutral-300 font-medium"
disabled={isSubmitting}
>
Cancel
</button>
<button
onClick={handleLog}
className={`px-4 py-2 bg-blue-600 text-white rounded-md font-medium flex items-center gap-2 ${
isSubmitting ? "opacity-50 cursor-not-allowed" : "hover:bg-blue-700"
}`}
disabled={isSubmitting}
>
{isSubmitting ? (
<>
<svg
className="animate-spin h-5 w-5 text-white"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
Logging...
</>
) : (
"Log Pallet"
)}
</button>
</div>
</div>
</div>
);
}
// Modal Component for Editing Artefact
function EditModal({ artefact, onClose }: { artefact: ExtendedArtefact; onClose: () => void }) {
const [name, setName] = useState(artefact.name);
const [type, setType] = useState(artefact.type);
const [description, setDescription] = useState(artefact.description);
const [location, setLocation] = useState(artefact.location);
const [warehouseArea, setWarehouseArea] = useState(artefact.warehouseArea);
const [earthquakeCode, setEarthquakeCode] = useState(artefact.earthquakeCode);
const [isRequired, setIsRequired] = useState(artefact.isRequired);
const [isSold, setIsSold] = useState(artefact.isSold);
const [isCollected, setIsCollected] = useState(artefact.isCollected);
const [createdAt, setDateAdded] = useState(new Date(artefact.createdAt).toLocaleDateString("en-GB"));
const [image, setImage] = useState<File | null>(null);
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const handleOverlayClick = (e: { target: any; currentTarget: any }) => {
function handleOverlayClick(e: { target: any; currentTarget: any }) {
if (e.target === e.currentTarget) {
onClose();
}
};
}
const handleSave = async () => {
if (!name || !description || !location || !earthquakeCode || !createdAt) {
async function handleSave() {
if (!name || !type || !description || !earthquakeCode || !warehouseArea) {
setError("All fields are required.");
return;
}
if (!validateEarthquakeCode(earthquakeCode)) {
setError("Earthquake Code must be in format: XX-M.M-Country-##### (e.g., EC-3.9-Belgium-05467)");
return;
}
setIsSubmitting(true);
try {
await new Promise((resolve) => setTimeout(resolve, 500)); // Simulated API call
const formData = new FormData();
formData.append("id", artefact.id.toString());
formData.append("name", name);
formData.append("type", type);
formData.append("description", description);
formData.append("earthquakeCode", earthquakeCode);
formData.append("warehouseArea", warehouseArea);
formData.append("isRequired", isRequired.toString());
formData.append("isSold", isSold.toString());
formData.append("isCollected", isCollected.toString());
if (image) {
formData.append("image", image);
}
await axios.post("/api/warehouse/edit-artefact", formData, {
headers: { "Content-Type": "multipart/form-data" },
});
alert(`Updated artefact ${name}`);
onClose();
} catch {
@ -372,7 +418,22 @@ function EditModal({ artefact, onClose }: { artefact: ExtendedArtefact; onClose:
} finally {
setIsSubmitting(false);
}
};
}
function handleImageChange(e: React.ChangeEvent<HTMLInputElement>) {
if (e.target.files && e.target.files[0]) {
const file = e.target.files[0];
if (file.size > 5 * 1024 * 1024) {
setError("Image size must be less than 5MB");
return;
}
if (!["image/jpeg", "image/png"].includes(file.type)) {
setError("Only JPEG or PNG images are allowed");
return;
}
setImage(file);
}
}
return (
<div
@ -383,15 +444,46 @@ function EditModal({ artefact, onClose }: { artefact: ExtendedArtefact; onClose:
<h3 className="text-lg font-semibold mb-4 text-neutral-800">Edit Artefact</h3>
{error && <p className="text-red-600 text-sm mb-2">{error}</p>}
<div className="space-y-2">
{artefact.imageName && (
<div className="mb-2">
<Image
src={`/uploads/${artefact.imageName}`}
alt="Artefact"
width={200}
height={200}
className="object-cover rounded-md"
/>
</div>
)}
<input
type="file"
accept="image/jpeg,image/png"
onChange={handleImageChange}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Artefact Image"
disabled={isSubmitting}
/>
<p className="text-sm text-neutral-600">Created At: {new Date(artefact.createdAt).toLocaleDateString("en-GB")}</p>
<input
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Artefact Name"
disabled={isSubmitting}
/>
<input
type="text"
placeholder="Type (e.g., Lava, Tephra, Ash)"
value={type}
onChange={(e) => setType(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Artefact Type"
disabled={isSubmitting}
/>
<textarea
placeholder="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 h-16"
@ -400,20 +492,22 @@ function EditModal({ artefact, onClose }: { artefact: ExtendedArtefact; onClose:
/>
<input
type="text"
value={location}
onChange={(e) => setLocation(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Artefact Location"
disabled={isSubmitting}
/>
<input
type="text"
placeholder="Earthquake Code (e.g., EC-3.9-Belgium-05467)"
value={earthquakeCode}
onChange={(e) => setEarthquakeCode(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Earthquake ID"
disabled={isSubmitting}
/>
<input
type="text"
placeholder="Warehouse Area (e.g., A-12)"
value={warehouseArea}
onChange={(e) => setWarehouseArea(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500"
aria-label="Storage Location"
disabled={isSubmitting}
/>
<div className="flex items-center gap-2">
<input
type="checkbox"
@ -430,7 +524,7 @@ function EditModal({ artefact, onClose }: { artefact: ExtendedArtefact; onClose:
type="checkbox"
checked={isSold}
onChange={(e) => setIsSold(e.target.checked)}
className="h-4 w-4 text-blue-600 border-neutral-300 rounded focus:ring-blue-500"
className="w-4 h-4 text-blue-600 border-neutral-300 rounded focus:ring-blue-500"
aria-label="Sold Artefact"
disabled={isSubmitting}
/>
@ -447,14 +541,6 @@ function EditModal({ artefact, onClose }: { artefact: ExtendedArtefact; onClose:
/>
<label className="text-sm text-neutral-600">Collected</label>
</div>
<input
type="date"
value={createdAt}
onChange={(e) => setDateAdded(e.target.value)}
className="w-full p-2 border border-neutral-300 rounded-md focus:ring-2 focus:ring-blue-500"
aria-label="Date Added"
disabled={isSubmitting}
/>
</div>
<div className="flex justify-end gap-3 mt-4">
<button
@ -483,7 +569,7 @@ function EditModal({ artefact, onClose }: { artefact: ExtendedArtefact; onClose:
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V723C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
Saving...

View File

@ -10,7 +10,6 @@ interface AuthModalProps {
}
export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
// todo add login successful message
const [isLogin, setIsLogin] = useState<boolean>(true);
const modalRef = useRef<HTMLDivElement>(null);
const [isFailed, setIsFailed] = useState<boolean>(false);

View File

@ -23,8 +23,6 @@ const COLUMNS = [
{ label: "Date", key: "date" },
];
// todo modify slightly
export default function EarthquakeSearchModal({
open,
onClose,

View File

@ -1,4 +1,4 @@
export async function passwordStrengthCheck(password: string): Promise<string> {
export function passwordStrengthCheck(password: string): string {
if (password.length < 8) {
return "short";
} else if (password.length > 16) {
@ -21,3 +21,24 @@ export async function passwordStrengthCheck(password: string): Promise<string> {
}
return "end of function";
}
export function validatePassword(password: string) {
const result = passwordStrengthCheck(password);
switch (result) {
case "short":
return { message: "Password is shorter than 8 characters", status: 400 };
case "long":
return { message: "Password is longer than 16 characters", status: 400 };
case "no lower":
return { message: "Password must contain lowercase letters", status: 400 };
case "no upper":
return { message: "Password must contain uppercase letters", status: 400 };
case "no digit":
return { message: "Password must contain a number", status: 400 };
case "no special":
return { message: "Password must contain a special character (!@#$%^&*)", status: 400 };
default:
return {};
}
}