Added shop receiving route

This commit is contained in:
Tim Howitz 2025-06-02 08:16:23 +01:00
parent 976eaf7653
commit f3ad2c8ed8
3 changed files with 103 additions and 47 deletions

View File

@ -3,50 +3,50 @@ import { prisma } from "@utils/prisma";
// Generates code using only the country, and highest id in DB for numbering
async function generateEarthquakeCode(type: string, country: string) {
const typeLetter = type.trim().charAt(0).toUpperCase();
// Remove non-alphanumeric for the country part
const countrySlug = (country || "Unknown").replace(/[^\w]/gi, "");
// Use highest DB id to find the latest added earthquake's code number
const last = await prisma.earthquake.findFirst({
orderBy: { id: "desc" },
select: { code: true }
});
let num = 10000;
if (last?.code) {
const parts = last.code.split("-");
const lastNum = parseInt(parts[parts.length - 1], 10);
if (!isNaN(lastNum)) num = lastNum + 1;
}
return `E${typeLetter}-${countrySlug}-${num.toString().padStart(5, "0")}`;
const typeLetter = type.trim().charAt(0).toUpperCase();
// Remove non-alphanumeric for the country part
const countrySlug = (country || "Unknown").replace(/[^\w]/gi, "");
// Use highest DB id to find the latest added earthquake's code number
const last = await prisma.earthquake.findFirst({
orderBy: { id: "desc" },
select: { code: true },
});
let num = 10000;
if (last?.code) {
const parts = last.code.split("-");
const lastNum = parseInt(parts[parts.length - 1], 10);
if (!isNaN(lastNum)) num = lastNum + 1;
}
return `E${typeLetter}-${countrySlug}-${num.toString().padStart(5, "0")}`;
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { date, magnitude, type, location, latitude, longitude, depth, country } = body;
const creatorId = 1;
if (!date || !magnitude || !type || !location || !latitude || !longitude || !depth || !country) {
return NextResponse.json({ error: "Missing fields" }, { status: 400 });
}
if (+magnitude > 10) {
return NextResponse.json({ error: "Magnitude cannot exceed 10" }, { status: 400 });
}
const code = await generateEarthquakeCode(type, country);
const eq = await prisma.earthquake.create({
data: {
date: new Date(date),
code,
magnitude: +magnitude,
type,
location, // "city, country"
latitude: +latitude,
longitude: +longitude,
depth,
creatorId,
}
});
return NextResponse.json({ id: eq.id, code }, { status: 201 });
} catch (e: any) {
return NextResponse.json({ error: e.message }, { status: 500 });
}
try {
const body = await request.json();
const { date, magnitude, type, location, latitude, longitude, depth, country } = body;
const creatorId = 1;
if (!date || !magnitude || !type || !location || !latitude || !longitude || !depth || !country) {
return NextResponse.json({ error: "Missing fields" }, { status: 400 });
}
if (+magnitude > 10) {
return NextResponse.json({ error: "Magnitude cannot exceed 10" }, { status: 400 });
}
const code = await generateEarthquakeCode(type, country);
const eq = await prisma.earthquake.create({
data: {
date: new Date(date),
code,
magnitude: +magnitude,
type,
location, // "city, country"
latitude: +latitude,
longitude: +longitude,
depth,
creatorId,
},
});
return NextResponse.json({ id: eq.id, code }, { status: 201 });
} catch (e: any) {
return NextResponse.json({ error: e.message }, { status: 500 });
}
}

View File

@ -0,0 +1,50 @@
import { prisma } from "@utils/prisma";
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { ExtendedArtefact } from "@appTypes/ApiTypes";
interface SuperExtendedArtefact extends ExtendedArtefact {
location: string;
dateReleased: string;
image: string;
price: number;
}
export async function POST(request: NextRequest) {
try {
const {
artefacts,
email,
orderNumber,
userId,
}: { artefacts: SuperExtendedArtefact[]; email: string; orderNumber: string; userId: number | undefined } =
await request.json();
if (!email || !artefacts || !orderNumber) {
return NextResponse.json({ error: "Missing fields" }, { status: 401 });
}
const order = await prisma.order.create({
data: {
orderNumber,
email,
userId: userId,
artefacts: {
connect: artefacts.map((artefact) => ({ id: artefact.id })),
},
},
});
await prisma.artefact.updateMany({
where: { id: { in: artefacts.map((a) => a.id) } },
data: {
isSold: true,
},
});
return NextResponse.json({ order }, { status: 201 });
} catch (error) {
console.error("Error creating order:", error);
return NextResponse.json({ error: "Failed to create order" }, { status: 500 });
}
}

View File

@ -292,13 +292,19 @@ export default function Shop() {
// remove all artefacts that were bought (works for both cart and single)
setHiddenArtefactIds((ids) => [...ids, ...artefactsToBuy.map((a) => a.id)]);
//!! todo create receiving api route
const genOrder = () => "#" + Math.random().toString(36).substring(2, 10).toUpperCase();
const genOrder = () =>
"#" + 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", artefactsToBuy);
const response = await axios.post("/api/shop/purchase", {
artefacts: artefactsToBuy,
email: paymentEmail,
orderNumber: orderNum,
userId: user?.id,
});
setOrderNumber(orderNum);
onClose();
setShowThankYouModal(true);
@ -469,7 +475,7 @@ export default function Shop() {
</p>
<div className="w-full max-w-7xl grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-10 p-2">
{currentArtefacts
.filter((x) => !hiddenArtefactIds.includes(x.id) && x.isRequired === false)
.filter((x) => !hiddenArtefactIds.includes(x.id) && x.isRequired === false && x.isSold === false)
.map((artefact) => (
<ArtefactCard key={artefact.id} artefact={artefact} />
))}