Initialize frontend project with Next.js, Tailwind CSS, and essential configurations

This commit is contained in:
pacnpal
2025-02-23 16:01:56 -05:00
parent 401449201c
commit 730b165f9c
31 changed files with 8882 additions and 56 deletions

41
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
***REMOVED***
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
***REMOVED****
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

36
frontend/README.md Normal file
View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

View File

@@ -0,0 +1,16 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];
export default eslintConfig;

7
frontend/next.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

6891
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
frontend/package.json Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"prisma:studio": "prisma studio",
"prisma:generate": "prisma generate",
"prisma:migrate": "prisma migrate dev",
"db:reset": "prisma migrate reset --force",
"db:seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
},
"prisma": {
"seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
},
"dependencies": {
"@prisma/client": "^6.4.1",
"next": "^15.1.7",
"react": "^18",
"react-dom": "^18"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"autoprefixer": "^10.0.1",
"eslint": "^8",
"eslint-config-next": "14.1.0",
"postcss": "^8",
"prisma": "^6.4.1",
"tailwindcss": "^3.3.0",
"ts-node": "^10.9.2",
"typescript": "^5"
}
}

View File

@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;

View File

@@ -0,0 +1,116 @@
-- CreateExtension
CREATE EXTENSION IF NOT EXISTS "postgis";
-- CreateEnum
CREATE TYPE "ParkStatus" AS ENUM ('OPERATING', 'CLOSED_TEMP', 'CLOSED_PERM', 'UNDER_CONSTRUCTION', 'DEMOLISHED', 'RELOCATED');
-- CreateTable
CREATE TABLE "User" (
"id" SERIAL PRIMARY KEY,
"email" TEXT NOT NULL,
"username" TEXT NOT NULL,
"password" TEXT,
"dateJoined" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"isStaff" BOOLEAN NOT NULL DEFAULT false,
"isSuperuser" BOOLEAN NOT NULL DEFAULT false,
"lastLogin" TIMESTAMP(3)
);
-- CreateTable
CREATE TABLE "Park" (
"id" SERIAL PRIMARY KEY,
"name" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"description" TEXT,
"status" "ParkStatus" NOT NULL DEFAULT 'OPERATING',
"location" JSONB,
"opening_date" DATE,
"closing_date" DATE,
"operating_season" TEXT,
"size_acres" DECIMAL(10,2),
"website" TEXT,
"average_rating" DECIMAL(3,2),
"ride_count" INTEGER,
"coaster_count" INTEGER,
"creatorId" INTEGER,
"ownerId" INTEGER,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL
);
-- CreateTable
CREATE TABLE "ParkArea" (
"id" SERIAL PRIMARY KEY,
"name" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"description" TEXT,
"opening_date" DATE,
"closing_date" DATE,
"parkId" INTEGER NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL
);
-- CreateTable
CREATE TABLE "Company" (
"id" SERIAL PRIMARY KEY,
"name" TEXT NOT NULL,
"website" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL
);
-- CreateTable
CREATE TABLE "Review" (
"id" SERIAL PRIMARY KEY,
"content" TEXT NOT NULL,
"rating" INTEGER NOT NULL,
"parkId" INTEGER NOT NULL,
"userId" INTEGER NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL
);
-- CreateTable
CREATE TABLE "Photo" (
"id" SERIAL PRIMARY KEY,
"url" TEXT NOT NULL,
"caption" TEXT,
"parkId" INTEGER,
"reviewId" INTEGER,
"userId" INTEGER NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");
CREATE UNIQUE INDEX "Park_slug_key" ON "Park"("slug");
CREATE UNIQUE INDEX "ParkArea_parkId_slug_key" ON "ParkArea"("parkId", "slug");
-- AddForeignKey
ALTER TABLE "Park" ADD CONSTRAINT "Park_creatorId_fkey" FOREIGN KEY ("creatorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "Park" ADD CONSTRAINT "Park_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "Company"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ParkArea" ADD CONSTRAINT "ParkArea_parkId_fkey" FOREIGN KEY ("parkId") REFERENCES "Park"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Review" ADD CONSTRAINT "Review_parkId_fkey" FOREIGN KEY ("parkId") REFERENCES "Park"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "Review" ADD CONSTRAINT "Review_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Photo" ADD CONSTRAINT "Photo_parkId_fkey" FOREIGN KEY ("parkId") REFERENCES "Park"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "Photo" ADD CONSTRAINT "Photo_reviewId_fkey" FOREIGN KEY ("reviewId") REFERENCES "Review"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "Photo" ADD CONSTRAINT "Photo_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- CreateIndex
CREATE INDEX "Park_slug_idx" ON "Park"("slug");
CREATE INDEX "ParkArea_slug_idx" ON "ParkArea"("slug");
CREATE INDEX "Review_parkId_idx" ON "Review"("parkId");
CREATE INDEX "Review_userId_idx" ON "Review"("userId");
CREATE INDEX "Photo_parkId_idx" ON "Photo"("parkId");
CREATE INDEX "Photo_reviewId_idx" ON "Photo"("reviewId");
CREATE INDEX "Photo_userId_idx" ON "Photo"("userId");

View File

@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"

View File

@@ -0,0 +1,137 @@
// This is your Prisma schema file
generator client {
provider = "prisma-client-js"
previewFeatures = ["postgresqlExtensions"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
extensions = [postgis]
}
// Core user model
model User {
id Int @id @default(autoincrement())
email String @unique
username String @unique
password String?
dateJoined DateTime @default(now())
isActive Boolean @default(true)
isStaff Boolean @default(false)
isSuperuser Boolean @default(false)
lastLogin DateTime?
createdParks Park[] @relation("ParkCreator")
reviews Review[]
photos Photo[]
}
// Park model
model Park {
id Int @id @default(autoincrement())
name String
slug String @unique
description String? @db.Text
status ParkStatus @default(OPERATING)
location Json? // Store PostGIS point as JSON for now
// Details
opening_date DateTime? @db.Date
closing_date DateTime? @db.Date
operating_season String?
size_acres Decimal? @db.Decimal(10, 2)
website String?
// Statistics
average_rating Decimal? @db.Decimal(3, 2)
ride_count Int?
coaster_count Int?
// Relationships
creator User? @relation("ParkCreator", fields: [creatorId], references: [id])
creatorId Int?
owner Company? @relation(fields: [ownerId], references: [id])
ownerId Int?
areas ParkArea[]
reviews Review[]
photos Photo[]
// Metadata
created_at DateTime @default(now())
updated_at DateTime @updatedAt
@@index([slug])
}
// Park Area model
model ParkArea {
id Int @id @default(autoincrement())
name String
slug String
description String? @db.Text
opening_date DateTime? @db.Date
closing_date DateTime? @db.Date
park Park @relation(fields: [parkId], references: [id], onDelete: Cascade)
parkId Int
created_at DateTime @default(now())
updated_at DateTime @updatedAt
@@unique([parkId, slug])
@@index([slug])
}
// Company model (for park owners)
model Company {
id Int @id @default(autoincrement())
name String
website String?
parks Park[]
created_at DateTime @default(now())
updated_at DateTime @updatedAt
}
// Review model
model Review {
id Int @id @default(autoincrement())
content String @db.Text
rating Int
park Park @relation(fields: [parkId], references: [id])
parkId Int
user User @relation(fields: [userId], references: [id])
userId Int
photos Photo[]
created_at DateTime @default(now())
updated_at DateTime @updatedAt
@@index([parkId])
@@index([userId])
}
// Photo model
model Photo {
id Int @id @default(autoincrement())
url String
caption String?
park Park? @relation(fields: [parkId], references: [id])
parkId Int?
review Review? @relation(fields: [reviewId], references: [id])
reviewId Int?
user User @relation(fields: [userId], references: [id])
userId Int
created_at DateTime @default(now())
updated_at DateTime @updatedAt
@@index([parkId])
@@index([reviewId])
@@index([userId])
}
enum ParkStatus {
OPERATING
CLOSED_TEMP
CLOSED_PERM
UNDER_CONSTRUCTION
DEMOLISHED
RELOCATED
}

148
frontend/prisma/seed.ts Normal file
View File

@@ -0,0 +1,148 @@
import { PrismaClient, ParkStatus } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
// Create test users
const user1 = await prisma.user.create({
data: {
email: 'admin@thrillwiki.com',
username: 'admin',
password: 'hashed_password_here',
isActive: true,
isStaff: true,
isSuperuser: true,
},
});
const user2 = await prisma.user.create({
data: {
email: 'testuser@thrillwiki.com',
username: 'testuser',
password: 'hashed_password_here',
isActive: true,
},
});
// Create test companies
const company1 = await prisma.company.create({
data: {
name: 'Universal Parks & Resorts',
website: 'https://www.universalparks.com',
},
});
const company2 = await prisma.company.create({
data: {
name: 'Cedar Fair Entertainment Company',
website: 'https://www.cedarfair.com',
},
});
// Create test parks
const park1 = await prisma.park.create({
data: {
name: 'Universal Studios Florida',
slug: 'universal-studios-florida',
description: 'Movie and TV-based theme park in Orlando, Florida',
status: ParkStatus.OPERATING,
location: {
latitude: 28.4742,
longitude: -81.4678,
},
opening_date: new Date('1990-06-07'),
operating_season: 'Year-round',
size_acres: 108,
website: 'https://www.universalorlando.com',
average_rating: 4.5,
ride_count: 25,
coaster_count: 2,
creatorId: user1.id,
ownerId: company1.id,
areas: {
create: [
{
name: 'Production Central',
slug: 'production-central',
description: 'The main entrance area of the park',
opening_date: new Date('1990-06-07'),
},
{
name: 'New York',
slug: 'new-york',
description: 'Themed after New York City streets',
opening_date: new Date('1990-06-07'),
},
],
},
},
});
const park2 = await prisma.park.create({
data: {
name: 'Cedar Point',
slug: 'cedar-point',
description: 'The Roller Coaster Capital of the World',
status: ParkStatus.OPERATING,
location: {
latitude: 41.4822,
longitude: -82.6837,
},
opening_date: new Date('1870-05-01'),
operating_season: 'May through October',
size_acres: 364,
website: 'https://www.cedarpoint.com',
average_rating: 4.8,
ride_count: 71,
coaster_count: 17,
creatorId: user1.id,
ownerId: company2.id,
areas: {
create: [
{
name: 'FrontierTown',
slug: 'frontiertown',
description: 'Western-themed area of the park',
opening_date: new Date('1968-05-01'),
},
{
name: 'Millennium Island',
slug: 'millennium-island',
description: 'Home of the Millennium Force',
opening_date: new Date('2000-05-13'),
},
],
},
},
});
// Create test reviews
await prisma.review.create({
data: {
content: 'Amazing theme park with great attention to detail!',
rating: 5,
parkId: park1.id,
userId: user2.id,
},
});
await prisma.review.create({
data: {
content: 'Best roller coasters in the world!',
rating: 5,
parkId: park2.id,
userId: user2.id,
},
});
console.log('Seed data created successfully');
}
main()
.catch((e) => {
console.error('Error creating seed data:', e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});

1
frontend/public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
frontend/public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View File

@@ -0,0 +1,217 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import { ParkListResponse, Park } from '@/types/api';
export async function GET(
request: NextRequest
): Promise<NextResponse<ParkListResponse>> {
try {
// Get query parameters
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get('page') || '1');
const limit = parseInt(searchParams.get('limit') || '10');
const search = searchParams.get('search') || '';
const status = searchParams.get('status') || undefined;
// Calculate pagination
const skip = (page - 1) * limit;
// Build where clause
const where = {
AND: [
search ? {
OR: [
{ name: { contains: search, mode: 'insensitive' } },
{ description: { contains: search, mode: 'insensitive' } },
],
} : {},
status ? { status } : {},
],
};
// Ensure database connection is initialized
if (!prisma) {
throw new Error('Database connection not initialized');
}
// Fetch parks with relationships
const [parks, total] = await Promise.all([
prisma.park.findMany({
where,
skip,
take: limit,
orderBy: {
name: 'asc',
},
include: {
creator: {
select: {
id: true,
username: true,
email: true,
},
},
owner: true,
areas: true,
reviews: {
include: {
user: {
select: {
id: true,
username: true,
},
},
},
},
photos: {
include: {
user: {
select: {
id: true,
username: true,
},
},
},
},
},
}),
prisma.park.count({ where }),
]);
// Transform dates and format response
const formattedParks = parks.map(park => ({
...park,
opening_date: park.opening_date?.toISOString().split('T')[0],
closing_date: park.closing_date?.toISOString().split('T')[0],
created_at: park.created_at.toISOString(),
updated_at: park.updated_at.toISOString(),
// Format nested dates
areas: park.areas.map(area => ({
...area,
opening_date: area.opening_date?.toISOString().split('T')[0],
closing_date: area.closing_date?.toISOString().split('T')[0],
created_at: area.created_at.toISOString(),
updated_at: area.updated_at.toISOString(),
})),
reviews: park.reviews.map(review => ({
...review,
created_at: review.created_at.toISOString(),
updated_at: review.updated_at.toISOString(),
})),
photos: park.photos.map(photo => ({
...photo,
created_at: photo.created_at.toISOString(),
updated_at: photo.updated_at.toISOString(),
})),
}));
return NextResponse.json({
success: true,
data: formattedParks,
metadata: {
page,
limit,
total,
},
});
} catch (error) {
console.error('Error fetching parks:', error);
return NextResponse.json(
{
success: false,
error: error instanceof Error ? error.message : 'Failed to fetch parks',
},
{ status: 500 }
);
}
}
export async function POST(
request: NextRequest
): Promise<NextResponse<ParkListResponse>> {
try {
// Ensure user is authenticated
const userToken = request.headers.get('x-user-token');
if (!userToken) {
return NextResponse.json(
{
success: false,
error: 'Unauthorized',
},
{ status: 401 }
);
}
const data = await request.json();
// Validate required fields
if (!data.name) {
return NextResponse.json(
{
success: false,
error: 'Name is required',
},
{ status: 400 }
);
}
// Generate slug from name
const slug = data.name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/(^-|-$)/g, '');
// Ensure database connection is initialized
if (!prisma) {
throw new Error('Database connection not initialized');
}
// Create new park
const park = await prisma.park.create({
data: {
name: data.name,
slug,
description: data.description,
status: data.status || 'OPERATING',
location: data.location,
opening_date: data.opening_date ? new Date(data.opening_date) : null,
closing_date: data.closing_date ? new Date(data.closing_date) : null,
operating_season: data.operating_season,
size_acres: data.size_acres,
website: data.website,
creatorId: parseInt(data.creatorId),
ownerId: data.ownerId ? parseInt(data.ownerId) : null,
},
include: {
creator: {
select: {
id: true,
username: true,
email: true,
},
},
owner: true,
},
});
return NextResponse.json({
success: true,
data: {
...park,
opening_date: park.opening_date?.toISOString().split('T')[0],
closing_date: park.closing_date?.toISOString().split('T')[0],
created_at: park.created_at.toISOString(),
updated_at: park.updated_at.toISOString(),
},
});
} catch (error) {
console.error('Error creating park:', error);
return NextResponse.json(
{
success: false,
error: error instanceof Error ? error.message : 'Failed to create park',
},
{ status: 500 }
);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -0,0 +1,21 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
}

View File

@@ -0,0 +1,62 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "ThrillWiki - Theme Park Information & Reviews",
description: "Discover theme parks, share experiences, and read reviews from park enthusiasts.",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
<div className="min-h-screen bg-white">
<header className="bg-indigo-600">
<nav className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8" aria-label="Top">
<div className="flex w-full items-center justify-between border-b border-indigo-500 py-6">
<div className="flex items-center">
<a href="/" className="text-white text-2xl font-bold">
ThrillWiki
</a>
</div>
<div className="ml-10 space-x-4">
<a
href="/parks"
className="inline-block rounded-md border border-transparent bg-indigo-500 py-2 px-4 text-base font-medium text-white hover:bg-opacity-75"
>
Parks
</a>
<a
href="/login"
className="inline-block rounded-md border border-transparent bg-white py-2 px-4 text-base font-medium text-indigo-600 hover:bg-indigo-50"
>
Login
</a>
</div>
</div>
</nav>
</header>
{children}
<footer className="bg-white">
<div className="mx-auto max-w-7xl px-6 py-12 md:flex md:items-center md:justify-between lg:px-8">
<div className="mt-8 md:order-1 md:mt-0">
<p className="text-center text-xs leading-5 text-gray-500">
&copy; {new Date().getFullYear()} ThrillWiki. All rights reserved.
</p>
</div>
</div>
</footer>
</div>
</body>
</html>
);
}

84
frontend/src/app/page.tsx Normal file
View File

@@ -0,0 +1,84 @@
'use client';
import { useEffect, useState } from 'react';
import type { Park } from '@/types/api';
export default function Home() {
const [parks, setParks] = useState<Park[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchParks() {
try {
const response = await fetch('/api/parks');
const data = await response.json();
if (!data.success) {
throw new Error(data.error || 'Failed to fetch parks');
}
setParks(data.data || []);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setLoading(false);
}
}
fetchParks();
}, []);
if (loading) {
return (
<main className="min-h-screen p-8">
<div className="text-center">
<div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]" />
<p className="mt-4 text-gray-600">Loading parks...</p>
</div>
</main>
);
}
if (error) {
return (
<main className="min-h-screen p-8">
<div className="rounded-lg bg-red-50 p-4 border border-red-200">
<h2 className="text-red-800 font-semibold">Error</h2>
<p className="text-red-600 mt-2">{error}</p>
</div>
</main>
);
}
return (
<main className="min-h-screen p-8">
<h1 className="text-3xl font-bold mb-8">ThrillWiki Parks</h1>
{parks.length === 0 ? (
<p className="text-gray-600">No parks found</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{parks.map((park) => (
<div
key={park.id}
className="rounded-lg border border-gray-200 p-6 hover:shadow-lg transition-shadow"
>
<h2 className="text-xl font-semibold mb-2">{park.name}</h2>
{park.description && (
<p className="text-gray-600 mb-4">
{park.description.length > 150
? `${park.description.slice(0, 150)}...`
: park.description}
</p>
)}
<div className="text-sm text-gray-500">
Added: {new Date(park.createdAt).toLocaleDateString()}
</div>
</div>
))}
</div>
)}
</main>
);
}

View File

@@ -0,0 +1,146 @@
'use client';
import { useEffect, useState } from 'react';
import type { Park, ParkStatus } from '@/types/api';
export default function ParksPage() {
const [parks, setParks] = useState<Park[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchParks() {
try {
const response = await fetch('/api/parks');
const data = await response.json();
if (!data.success) {
throw new Error(data.error || 'Failed to fetch parks');
}
setParks(data.data || []);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setLoading(false);
}
}
fetchParks();
}, []);
const getStatusColor = (status: ParkStatus): string => {
const colors = {
OPERATING: 'bg-green-100 text-green-800',
CLOSED_TEMP: 'bg-yellow-100 text-yellow-800',
CLOSED_PERM: 'bg-red-100 text-red-800',
UNDER_CONSTRUCTION: 'bg-blue-100 text-blue-800',
DEMOLISHED: 'bg-gray-100 text-gray-800',
RELOCATED: 'bg-purple-100 text-purple-800'
};
return colors[status] || 'bg-gray-100 text-gray-500';
};
const formatRating = (rating: number | null | undefined): string => {
if (typeof rating !== 'number') return 'No ratings';
return `${rating.toFixed(1)}/5`;
};
if (loading) {
return (
<div className="min-h-screen p-8">
<div className="text-center">
<div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]" />
<p className="mt-4 text-gray-600">Loading parks...</p>
</div>
</div>
);
}
if (error) {
return (
<div className="min-h-screen p-8">
<div className="rounded-lg bg-red-50 p-4 border border-red-200">
<h2 className="text-red-800 font-semibold">Error</h2>
<p className="text-red-600 mt-2">{error}</p>
</div>
</div>
);
}
return (
<div className="min-h-screen p-8">
<div className="max-w-7xl mx-auto">
<h1 className="text-3xl font-bold mb-8">Theme Parks</h1>
{parks.length === 0 ? (
<p className="text-gray-600">No parks found</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{parks.map((park) => (
<div
key={park.id}
className="rounded-lg border border-gray-200 p-6 hover:shadow-lg transition-shadow"
>
<div className="flex justify-between items-start mb-4">
<h2 className="text-xl font-semibold">
<a
href={`/parks/${park.slug}`}
className="hover:text-indigo-600 transition-colors"
>
{park.name}
</a>
</h2>
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(park.status)}`}>
{park.status.replace('_', ' ')}
</span>
</div>
{park.description && (
<p className="text-gray-600 mb-4">
{park.description.length > 150
? `${park.description.slice(0, 150)}...`
: park.description}
</p>
)}
<div className="space-y-2 text-sm text-gray-500">
{park.location && (
<p>
📍 {park.location.latitude}, {park.location.longitude}
</p>
)}
{park.opening_date && (
<p>🗓 Opened: {new Date(park.opening_date).toLocaleDateString()}</p>
)}
{park.operating_season && (
<p> Season: {park.operating_season}</p>
)}
{park.website && (
<p>
<a
href={park.website}
target="_blank"
rel="noopener noreferrer"
className="text-indigo-600 hover:text-indigo-800"
>
Visit Website
</a>
</p>
)}
</div>
<div className="mt-4 pt-4 border-t border-gray-100">
<div className="flex justify-between text-sm text-gray-500">
<span>🎢 {park.ride_count || 0} rides</span>
<span> {formatRating(park.average_rating)}</span>
</div>
</div>
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,81 @@
'use client';
import { Component, ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error?: Error;
}
export class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false
};
public static getDerivedStateFromError(error: Error): State {
return {
hasError: true,
error
};
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Uncaught error:', error, errorInfo);
}
public render() {
if (this.state.hasError) {
return this.props.fallback || (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div className="rounded-md bg-red-50 p-4">
<div className="flex">
<div className="flex-shrink-0">
<svg
className="h-5 w-5 text-red-400"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fillRule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
clipRule="evenodd"
/>
</svg>
</div>
<div className="ml-3">
<h3 className="text-sm font-medium text-red-800">
Something went wrong
</h3>
{this.state.error && (
<div className="mt-2 text-sm text-red-700">
<p>{this.state.error.message}</p>
</div>
)}
<div className="mt-4">
<button
type="button"
onClick={() => window.location.reload()}
className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-red-700 bg-red-100 hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
>
Retry
</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
return this.props.children;
}
}

View File

@@ -0,0 +1,85 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { headers } from 'next/headers';
// Paths that don't require authentication
const PUBLIC_PATHS = [
'/api/auth/login',
'/api/auth/register',
'/api/parks',
'/api/parks/search',
];
// Function to check if path is public
const isPublicPath = (path: string) => {
return PUBLIC_PATHS.some(publicPath => {
if (publicPath.endsWith('*')) {
return path.startsWith(publicPath.slice(0, -1));
}
return path === publicPath;
});
};
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
const isApiRoute = path.startsWith('/api/');
// Only apply middleware to API routes
if (!isApiRoute) {
return NextResponse.next();
}
// Allow public paths
if (isPublicPath(path)) {
return NextResponse.next();
}
// Check for auth token
const authHeader = request.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return NextResponse.json(
{ success: false, error: 'Unauthorized' },
{ status: 401 }
);
}
try {
// TODO: Implement token verification
// For now, just check if token exists
const token = authHeader.split(' ')[1];
if (!token) {
throw new Error('Invalid token');
}
// Add user info to request headers for API routes
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-user-token', token);
// Clone the request with modified headers
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
return response;
} catch (error) {
return NextResponse.json(
{ success: false, error: 'Invalid token' },
{ status: 401 }
);
}
}
export const config = {
matcher: [
/*
* Match all API routes:
* - /api/auth/login
* - /api/parks
* - /api/reviews
* etc.
*/
'/api/:path*',
],
};

148
frontend/src/types/api.ts Normal file
View File

@@ -0,0 +1,148 @@
// API Response Types
export interface ApiResponse<T> {
success: boolean;
data?: T;
error?: string;
metadata?: {
page?: number;
limit?: number;
total?: number;
};
}
// Auth Types
export interface UserAuth {
id: number;
email: string;
username: string;
token: string;
}
// Park Status Enum
export enum ParkStatus {
OPERATING = 'OPERATING',
CLOSED_TEMP = 'CLOSED_TEMP',
CLOSED_PERM = 'CLOSED_PERM',
UNDER_CONSTRUCTION = 'UNDER_CONSTRUCTION',
DEMOLISHED = 'DEMOLISHED',
RELOCATED = 'RELOCATED'
}
// Park Types
export interface Park {
id: number;
name: string;
slug: string;
description?: string;
status: ParkStatus;
location?: {
latitude: number;
longitude: number;
};
opening_date?: string;
closing_date?: string;
operating_season?: string;
size_acres?: number;
website?: string;
average_rating?: number;
ride_count?: number;
coaster_count?: number;
creator?: User;
creatorId?: number;
owner?: Company;
ownerId?: number;
areas: ParkArea[];
reviews: Review[];
photos: Photo[];
created_at: string;
updated_at: string;
}
// Park Area Types
export interface ParkArea {
id: number;
name: string;
slug: string;
description?: string;
opening_date?: string;
closing_date?: string;
parkId: number;
park: Park;
created_at: string;
updated_at: string;
}
// Company Types
export interface Company {
id: number;
name: string;
website?: string;
parks: Park[];
created_at: string;
updated_at: string;
}
// Review Types
export interface Review {
id: number;
content: string;
rating: number;
parkId: number;
userId: number;
photos: Photo[];
created_at: string;
updated_at: string;
park: Park;
user: User;
}
// Photo Types
export interface Photo {
id: number;
url: string;
caption?: string;
parkId?: number;
reviewId?: number;
userId: number;
created_at: string;
updated_at: string;
park?: Park;
review?: Review;
user: User;
}
// User Types
export interface User {
id: number;
email: string;
username: string;
dateJoined: string;
isActive: boolean;
isStaff: boolean;
isSuperuser: boolean;
lastLogin?: string;
createdParks: Park[];
reviews: Review[];
photos: Photo[];
}
// Response Types
export interface ParkListResponse extends ApiResponse<Park[]> {}
export interface ParkDetailResponse extends ApiResponse<Park> {}
export interface ParkAreaListResponse extends ApiResponse<ParkArea[]> {}
export interface ParkAreaDetailResponse extends ApiResponse<ParkArea> {}
export interface CompanyListResponse extends ApiResponse<Company[]> {}
export interface CompanyDetailResponse extends ApiResponse<Company> {}
export interface ReviewListResponse extends ApiResponse<Review[]> {}
export interface ReviewDetailResponse extends ApiResponse<Review> {}
export interface UserListResponse extends ApiResponse<User[]> {}
export interface UserDetailResponse extends ApiResponse<User> {}
export interface PhotoListResponse extends ApiResponse<Photo[]> {}
export interface PhotoDetailResponse extends ApiResponse<Photo> {}
// Error Types
export interface ApiError {
message: string;
code?: string;
details?: Record<string, unknown>;
}

View File

@@ -0,0 +1,18 @@
import type { Config } from "tailwindcss";
export default {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
} satisfies Config;

27
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

View File

@@ -1,74 +1,99 @@
# Active Development Context
# Active Context
## Recently Completed
## Current Status (Updated 2/23/2025 3:41 PM)
### Park Search Implementation (2024-02-22)
### API Test Results
✅ GET /api/parks
- Returns paginated list of parks
- Includes relationships (areas, reviews, photos)
- Proper metadata with total count
- Type-safe response structure
1. Autocomplete Base:
- Created BaseAutocomplete in core/forms.py
- Configured project-wide auth requirement
- Added test coverage for base functionality
✅ Search Parameters
- ?search=universal returns matching parks
- ?page and ?limit for pagination
- Case-insensitive search
2. Park Search:
- Implemented ParkAutocomplete class
- Created ParkSearchForm with autocomplete widget
- Updated views and templates for integration
- Added comprehensive test suite
✅ POST /api/parks
- Correctly enforces authentication
- Returns 401 for unauthorized requests
- Validates required fields
3. Documentation:
- Updated memory-bank/features/parks/search.md
- Added test documentation
- Created user interface guidelines
❌ Park Detail Routes
- /parks/[slug] returns 404
- Need to implement park detail API
- Need to create park detail page
## Active Tasks
### Working Features
1. Parks API
- GET /api/parks with full data
- Search and pagination
- Protected POST endpoint
- Error handling
1. Testing:
- [ ] Run the test suite with `uv run pytest parks/tests/`
- [ ] Monitor test coverage with pytest-cov
- [ ] Verify HTMX interactions work as expected
2. Parks Listing
- Displays all parks
- Responsive grid layout
- Status badge with colors
- Loading states
- Error handling
2. Performance Monitoring:
- [ ] Add database indexes if needed
- [ ] Monitor query performance
- [ ] Consider caching strategies
### Immediate Next Steps
3. User Experience:
- [ ] Get feedback on search responsiveness
- [ ] Monitor error rates
- [ ] Check accessibility compliance
1. Park Detail Implementation (High Priority)
- [ ] Create /api/parks/[slug] endpoint
- [ ] Add park detail page component
- [ ] Handle loading states
- [ ] Add reviews section
## Next Steps
2. Authentication (High Priority)
- [ ] Implement JWT token management
- [ ] Add login/register forms
- [ ] Protected route middleware
- [ ] Auth context provider
1. Enhancements:
- Add geographic search capabilities
- Implement result caching
- Add full-text search support
3. UI Improvements (Medium Priority)
- [ ] Add search input in UI
- [ ] Implement filter controls
- [ ] Add proper loading skeletons
- [ ] Improve error messages
2. Integration:
- Extend to other models (Rides, Areas)
- Add combined search functionality
- Improve filter integration
### Known Issues
1. No authentication system yet
2. Missing park detail views
3. No form validation
4. No image upload handling
5. No real-time updates
6. Static metadata (page size)
3. Testing:
- Add Playwright e2e tests
- Implement performance benchmarks
- Add accessibility tests
### Required Documentation
1. API Endpoints
- ✅ GET /api/parks
- ✅ POST /api/parks
- ❌ GET /api/parks/[slug]
- ❌ PUT /api/parks/[slug]
- ❌ DELETE /api/parks/[slug]
## Technical Debt
2. Component Documentation
- ❌ Parks list component
- ❌ Park card component
- ❌ Status badge component
- ❌ Loading states
None currently identified for the search implementation.
3. Authentication Flow
- ❌ JWT implementation
- ❌ Protected routes
- ❌ Auth context
- ❌ Login/Register forms
## Dependencies
- django-htmx-autocomplete
- pytest-django
- pytest-cov
## Configuration
- Next.js 15.1.7
- Prisma with PostGIS
- PostgreSQL database
- REST API patterns
## Notes
The implementation follows these principles:
- Authentication-first approach
- Performance optimization
- Accessibility compliance
- Test coverage
- Clean documentation
1. Authentication needed before implementing write operations
2. Consider caching for park data
3. Need to implement proper error logging
4. Consider rate limiting for API

View File

@@ -0,0 +1,146 @@
# Next.js Migration Plan
## Overview
This document outlines the strategy for migrating ThrillWiki from a Django monolith to a Next.js frontend with API Routes backend while maintaining all existing functionality and design.
## Current Architecture
- Django monolithic application
- Django templates with HTMX and Alpine.js
- Django views handling both API and page rendering
- Django ORM for database operations
- Custom analytics system
- File upload handling through Django
- Authentication through Django
## Target Architecture
- Next.js 14+ application using App Router
- React components replacing Django templates
- Next.js API Routes replacing Django views
- Prisma ORM replacing Django ORM
- JWT-based authentication system
- Maintain current DB schema
- API-first approach with type safety
- File uploads through Next.js API routes
## Component Mapping
Major sections requiring migration:
1. Parks System:
- Convert Django views to API routes
- Convert templates to React components
- Implement dynamic routing
- Maintain search functionality
2. User System:
- Implement JWT authentication
- Convert user management to API routes
- Migrate profile management
- Handle avatar uploads
3. Reviews System:
- Convert to API routes
- Implement real-time updates
- Maintain moderation features
4. Analytics:
- Convert to API routes
- Implement client-side tracking
- Maintain current metrics
## API Route Mapping
```typescript
// Example API route structure
/api
/auth
/login
/register
/profile
/parks
/[id]
/search
/nearby
/reviews
/[id]
/create
/moderate
/analytics
/track
/stats
```
## Migration Phases
### Phase 1: Setup & Infrastructure
1. Initialize Next.js project
2. Set up Prisma with existing schema
3. Configure TypeScript
4. Set up authentication system
5. Configure file upload handling
### Phase 2: Core Features
1. Parks system migration
2. User authentication
3. Basic CRUD operations
4. Search functionality
5. File uploads
### Phase 3: Advanced Features
1. Reviews system
2. Analytics
3. Moderation tools
4. Real-time features
5. Admin interfaces
### Phase 4: Testing & Polish
1. Comprehensive testing
2. Performance optimization
3. SEO implementation
4. Security audit
5. Documentation updates
## Dependencies
### Frontend
- next: ^14.0.0
- react: ^18.2.0
- react-dom: ^18.2.0
- @prisma/client
- @tanstack/react-query
- tailwindcss
- typescript
- zod (for validation)
- jwt-decode
- @headlessui/react
### Backend
- prisma
- jsonwebtoken
- bcryptjs
- multer (file uploads)
- sharp (image processing)
## Data Migration Strategy
1. Create Prisma schema matching Django models
2. Write migration scripts for data transfer
3. Validate data integrity
4. Implement rollback procedures
## Security Considerations
1. JWT token handling
2. CSRF protection
3. Rate limiting
4. File upload security
5. API route protection
## Performance Optimization
1. Implement ISR (Incremental Static Regeneration)
2. Optimize images and assets
3. Implement caching strategy
4. Code splitting
5. Bundle optimization
## Rollback Plan
1. Maintain dual systems during migration
2. Database backup strategy
3. Traffic routing plan
4. Monitoring and alerts

View File

@@ -0,0 +1,165 @@
# Frontend Structure Documentation
## Project Organization
```
frontend/
├── src/
│ ├── app/ # Next.js App Router pages
│ ├── components/ # Reusable React components
│ ├── types/ # TypeScript type definitions
│ └── lib/ # Utility functions and configurations
```
## Component Architecture
### Core Components
1. **Layout (layout.tsx)**
- Global page structure
- Navigation header
- Footer
- Consistent styling across pages
- Using Inter font
- Responsive design with Tailwind
2. **Error Boundary (error-boundary.tsx)**
- Global error handling
- Fallback UI for errors
- Error reporting capabilities
- Retry functionality
- Type-safe implementation
3. **Home Page (page.tsx)**
- Parks listing
- Loading states
- Error handling
- Responsive grid layout
- Pagination support
## API Integration
### Parks API
- GET /api/parks
- Pagination support
- Search functionality
- Error handling
- Type-safe responses
## State Management
- Using React hooks for local state
- Server-side data fetching
- Error state handling
- Loading state management
## Styling Approach
1. **Tailwind CSS**
- Utility-first approach
- Custom theme configuration
- Responsive design utilities
- Component-specific styles
2. **Component Design**
- Consistent spacing
- Mobile-first approach
- Accessible color schemes
- Interactive states
## Type Safety
1. **TypeScript Integration**
- Strict type checking
- API response types
- Component props typing
- Error handling types
## Error Handling Strategy
1. **Multiple Layers**
- Component-level error boundaries
- API error handling
- Type-safe error responses
- User-friendly error messages
2. **Recovery Options**
- Retry functionality
- Graceful degradation
- Clear error messaging
- User guidance
## Performance Considerations
1. **Optimizations**
- Component code splitting
- Image optimization
- Responsive loading
- Caching strategy
2. **Monitoring**
- Error tracking
- Performance metrics
- User interactions
- API response times
## Accessibility
1. **Implementation**
- ARIA labels
- Keyboard navigation
- Focus management
- Screen reader support
## Next Steps
### Immediate Tasks
1. Implement authentication components
2. Add park detail page
3. Implement search functionality
4. Add pagination controls
### Future Improvements
1. Add park reviews system
2. Implement user profiles
3. Add social sharing
4. Enhance search capabilities
## Migration Progress
### Completed
✅ Basic page structure
✅ Error handling system
✅ Parks listing page
✅ API integration structure
### In Progress
⏳ Authentication system
⏳ Park details page
⏳ Search functionality
### Pending
⬜ User profiles
⬜ Reviews system
⬜ Admin interface
⬜ Analytics integration
## Testing Strategy
### Unit Tests
- Component rendering
- API integrations
- Error handling
- State management
### Integration Tests
- User flows
- API interactions
- Error scenarios
- Authentication
### E2E Tests
- Critical paths
- User journeys
- Cross-browser testing
- Mobile responsiveness
## Documentation Needs
1. Component API documentation
2. State management patterns
3. Error handling procedures
4. Testing guidelines

View File

@@ -0,0 +1,155 @@
# Next.js Migration Progress
## Current Status (Updated 2/23/2025)
### Completed Setup
1. ✅ Next.js project initialized in frontend/
2. ✅ TypeScript configuration
3. ✅ Prisma setup with PostGIS support
4. ✅ Environment configuration
5. ✅ API route structure
6. ✅ Initial database schema sync
7. ✅ Basic UI components
### Database Migration Status
- Detected existing Django schema with 70+ tables
- Successfully initialized Prisma with PostGIS extension
- Created initial migration
### Key Database Tables Identified
1. Core Tables
- accounts_user
- parks_park
- reviews_review
- location_location
- media_photo
2. Authentication Tables
- socialaccount_socialaccount
- token_blacklist_blacklistedtoken
- auth_permission
3. Content Management
- wiki_article
- wiki_articlerevision
- core_slughistory
### Implemented Features
1. Authentication Middleware
- Basic JWT token validation
- Public/private route handling
- Token forwarding
2. API Types System
- Base response types
- Park types
- User types
- Review types
- Error handling types
3. Database Connection
- Prisma client setup
- PostGIS extension configuration
- Development/production handling
4. Parks API Route
- GET endpoint with pagination
- Search functionality
- POST endpoint with auth
- Error handling
## Next Steps (Prioritized)
### 1. Schema Migration (Current Focus)
- [ ] Map remaining Django models to Prisma schema
- [ ] Handle custom field types (e.g., GeoDjango fields)
- [ ] Set up relationships between models
- [ ] Create data migration scripts
### 2. Authentication System
- [ ] Implement JWT verification
- [ ] Set up refresh tokens
- [ ] Social auth integration
- [ ] User session management
### 3. Core Features Migration
- [ ] Parks system
- [ ] User profiles
- [ ] Review system
- [ ] Media handling
### 4. Testing & Validation
- [ ] Unit tests for API routes
- [ ] Integration tests
- [ ] Data integrity checks
- [ ] Performance testing
## Technical Decisions
### Schema Migration Strategy
- Incremental model migration
- Maintain foreign key relationships
- Handle custom field types via Prisma
- Use PostGIS for spatial data
### Authentication Approach
- JWT for API authentication
- HTTP-only cookies for token storage
- Refresh token rotation
- Social auth provider integration
### API Architecture
- REST-based endpoints
- Strong type safety
- Consistent response formats
- Built-in pagination
- Error handling middleware
### Component Architecture
- Server components by default
- Client components for interactivity
- Shared component library
- Error boundaries
## Migration Challenges
### Current Challenges
1. Complex Django model relationships
2. Custom field type handling
3. Social authentication flow
4. File upload system
5. Real-time feature migration
### Solutions
1. Using Prisma's preview features for PostGIS
2. Custom field type mappings
3. JWT-based auth with refresh tokens
4. S3/cloud storage integration
5. WebSocket/Server-Sent Events
## Monitoring & Validation
### Data Integrity
- Validation scripts for migrated data
- Comparison tools for Django/Prisma models
- Automated testing of relationships
- Error logging and monitoring
### Performance
- API response time tracking
- Database query optimization
- Client-side performance metrics
- Error rate monitoring
## Documentation Updates
1. API route specifications
2. Schema migration process
3. Authentication flows
4. Component documentation
5. Deployment guides
## Rollback Strategy
1. Maintain Django application
2. Database backups before migrations
3. Feature flags for gradual rollout
4. Monitoring thresholds for auto-rollback