Initial rtrips-online scaffold

Next.js 14 app with Prisma (PostgreSQL), Gemini NL parser,
Tailwind dark theme, Docker + Traefik deployment config.

Features:
- Landing page with teal/cyan branding
- NL input → Gemini 2.0 Flash parsing → structured trip data
- Full Prisma schema (trips, destinations, itinerary, bookings,
  expenses, packing items, collaborators)
- Trip CRUD API routes with all sub-entities
- Trip dashboard with tabbed views (overview, itinerary,
  destinations, bookings, budget, packing)
- Embedded rSpace canvas with full-screen mode
- Docker multi-stage build with security hardening
- Health check endpoint

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Jeff Emmett 2026-02-13 12:10:22 -07:00
commit 8c13f6ad71
34 changed files with 4153 additions and 0 deletions

12
.env.example Normal file
View File

@ -0,0 +1,12 @@
# Database
DATABASE_URL="postgresql://rtrips:changeme@localhost:5432/rtrips"
# AI - Gemini 2.0 Flash for NL parsing
GEMINI_API_KEY="your-gemini-api-key"
# rSpace integration
NEXT_PUBLIC_RSPACE_URL="https://rspace.online"
RSPACE_INTERNAL_URL="http://rspace-online:3000"
# EncryptID
NEXT_PUBLIC_ENCRYPTID_SERVER_URL="https://encryptid.jeffemmett.com"

32
.gitignore vendored Normal file
View File

@ -0,0 +1,32 @@
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env
.env*.local
# typescript
*.tsbuildinfo
next-env.d.ts

38
Dockerfile Normal file
View File

@ -0,0 +1,38 @@
FROM node:20-alpine AS base
# Dependencies stage
FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json* ./
COPY prisma ./prisma/
RUN npm ci || npm install
# Build stage
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npx prisma generate
RUN npm run build
# Production stage
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]

64
docker-compose.yml Normal file
View File

@ -0,0 +1,64 @@
services:
rtrips:
build: .
container_name: rtrips-online
restart: unless-stopped
environment:
- DATABASE_URL=postgresql://rtrips:${DB_PASSWORD}@rtrips-postgres:5432/rtrips
- GEMINI_API_KEY=${GEMINI_API_KEY}
- NEXT_PUBLIC_RSPACE_URL=${NEXT_PUBLIC_RSPACE_URL:-https://rspace.online}
- RSPACE_INTERNAL_URL=${RSPACE_INTERNAL_URL:-http://rspace-online:3000}
- NEXT_PUBLIC_ENCRYPTID_SERVER_URL=${NEXT_PUBLIC_ENCRYPTID_SERVER_URL:-https://encryptid.jeffemmett.com}
labels:
- "traefik.enable=true"
- "traefik.http.routers.rtrips.rule=Host(`rtrips.online`) || Host(`www.rtrips.online`)"
- "traefik.http.services.rtrips.loadbalancer.server.port=3000"
networks:
- traefik-public
- rtrips-internal
depends_on:
rtrips-postgres:
condition: service_healthy
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
read_only: true
tmpfs:
- /tmp
rtrips-postgres:
image: postgres:16-alpine
container_name: rtrips-postgres
restart: unless-stopped
environment:
- POSTGRES_USER=rtrips
- POSTGRES_PASSWORD=${DB_PASSWORD}
- POSTGRES_DB=rtrips
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- rtrips-internal
healthcheck:
test: ["CMD-SHELL", "pg_isready -U rtrips -d rtrips"]
interval: 5s
timeout: 5s
retries: 5
cap_drop:
- ALL
cap_add:
- DAC_OVERRIDE
- FOWNER
- SETGID
- SETUID
security_opt:
- no-new-privileges:true
networks:
traefik-public:
external: true
rtrips-internal:
internal: true
volumes:
postgres_data:

6
next.config.mjs Normal file
View File

@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
};
export default nextConfig;

1970
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

32
package.json Normal file
View File

@ -0,0 +1,32 @@
{
"name": "rtrips-online",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"db:push": "npx prisma db push",
"db:migrate": "npx prisma migrate dev",
"db:studio": "npx prisma studio"
},
"dependencies": {
"@prisma/client": "^6.19.2",
"date-fns": "^4.1.0",
"nanoid": "^5.0.9",
"next": "14.2.35",
"react": "^18",
"react-dom": "^18",
"zustand": "^5.0.11"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"postcss": "^8",
"prisma": "^6.19.2",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}

8
postcss.config.mjs Normal file
View File

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

225
prisma/schema.prisma Normal file
View File

@ -0,0 +1,225 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
// ─── Users ──────────────────────────────────────────────────────────
model User {
id String @id @default(cuid())
did String @unique // EncryptID DID
username String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
trips TripCollaborator[]
expenses Expense[]
packingItems PackingItem[]
}
// ─── Trips ──────────────────────────────────────────────────────────
model Trip {
id String @id @default(cuid())
title String
slug String @unique
description String? @db.Text
rawInput String? @db.Text // Original NL input preserved
startDate DateTime?
endDate DateTime?
budgetTotal Float?
budgetCurrency String @default("USD")
status TripStatus @default(PLANNING)
canvasSlug String? // rspace community slug
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
collaborators TripCollaborator[]
destinations Destination[]
itineraryItems ItineraryItem[]
bookings Booking[]
expenses Expense[]
packingItems PackingItem[]
}
enum TripStatus {
PLANNING
BOOKED
IN_PROGRESS
COMPLETED
CANCELLED
}
model TripCollaborator {
id String @id @default(cuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
tripId String
trip Trip @relation(fields: [tripId], references: [id], onDelete: Cascade)
role CollaboratorRole @default(MEMBER)
joinedAt DateTime @default(now())
@@unique([userId, tripId])
@@index([tripId])
}
enum CollaboratorRole {
OWNER
EDITOR
VIEWER
MEMBER
}
// ─── Destinations ───────────────────────────────────────────────────
model Destination {
id String @id @default(cuid())
tripId String
trip Trip @relation(fields: [tripId], references: [id], onDelete: Cascade)
name String
country String?
lat Float?
lng Float?
arrivalDate DateTime?
departureDate DateTime?
notes String? @db.Text
sortOrder Int @default(0)
canvasShapeId String? // ID of folk-destination on canvas
createdAt DateTime @default(now())
itineraryItems ItineraryItem[]
bookings Booking[]
@@index([tripId])
}
// ─── Itinerary ──────────────────────────────────────────────────────
model ItineraryItem {
id String @id @default(cuid())
tripId String
trip Trip @relation(fields: [tripId], references: [id], onDelete: Cascade)
destinationId String?
destination Destination? @relation(fields: [destinationId], references: [id], onDelete: SetNull)
title String
description String? @db.Text
date DateTime?
startTime String? // "09:00" format
endTime String? // "17:00" format
category ItineraryCategory @default(ACTIVITY)
sortOrder Int @default(0)
canvasShapeId String?
createdAt DateTime @default(now())
@@index([tripId])
@@index([destinationId])
}
enum ItineraryCategory {
FLIGHT
TRANSPORT
ACCOMMODATION
ACTIVITY
MEAL
FREE_TIME
OTHER
}
// ─── Bookings ───────────────────────────────────────────────────────
model Booking {
id String @id @default(cuid())
tripId String
trip Trip @relation(fields: [tripId], references: [id], onDelete: Cascade)
destinationId String?
destination Destination? @relation(fields: [destinationId], references: [id], onDelete: SetNull)
type BookingType
provider String? // "Air Canada", "Booking.com"
confirmationNumber String?
details String? @db.Text // JSON for flexible data
cost Float?
currency String @default("USD")
startDate DateTime?
endDate DateTime?
status BookingStatus @default(PLANNED)
canvasShapeId String?
createdAt DateTime @default(now())
@@index([tripId])
}
enum BookingType {
FLIGHT
HOTEL
CAR_RENTAL
TRAIN
BUS
FERRY
ACTIVITY
RESTAURANT
OTHER
}
enum BookingStatus {
PLANNED
BOOKED
CONFIRMED
CANCELLED
}
// ─── Expenses ───────────────────────────────────────────────────────
model Expense {
id String @id @default(cuid())
tripId String
trip Trip @relation(fields: [tripId], references: [id], onDelete: Cascade)
paidById String?
paidBy User? @relation(fields: [paidById], references: [id], onDelete: SetNull)
description String
amount Float
currency String @default("USD")
category ExpenseCategory @default(OTHER)
date DateTime?
splitType SplitType @default(EQUAL)
createdAt DateTime @default(now())
@@index([tripId])
}
enum ExpenseCategory {
FLIGHT
ACCOMMODATION
FOOD
TRANSPORT
ACTIVITY
SHOPPING
OTHER
}
enum SplitType {
EQUAL
CUSTOM
INDIVIDUAL
}
// ─── Packing ────────────────────────────────────────────────────────
model PackingItem {
id String @id @default(cuid())
tripId String
trip Trip @relation(fields: [tripId], references: [id], onDelete: Cascade)
addedById String?
addedBy User? @relation(fields: [addedById], references: [id], onDelete: SetNull)
name String
category String? // "Clothing", "Electronics", "Documents"
packed Boolean @default(false)
quantity Int @default(1)
sortOrder Int @default(0)
createdAt DateTime @default(now())
@@index([tripId])
}

View File

@ -0,0 +1,5 @@
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({ status: 'ok', service: 'rtrips-online' });
}

View File

@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const body = await request.json();
const booking = await prisma.booking.create({
data: {
tripId: params.id,
destinationId: body.destinationId,
type: body.type,
provider: body.provider,
confirmationNumber: body.confirmationNumber,
details: body.details,
cost: body.cost,
currency: body.currency || 'USD',
startDate: body.startDate ? new Date(body.startDate) : null,
endDate: body.endDate ? new Date(body.endDate) : null,
status: body.status || 'PLANNED',
},
});
return NextResponse.json(booking, { status: 201 });
} catch (error) {
console.error('Create booking error:', error);
return NextResponse.json({ error: 'Failed to create booking' }, { status: 500 });
}
}

View File

@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const body = await request.json();
const destination = await prisma.destination.create({
data: {
tripId: params.id,
name: body.name,
country: body.country,
lat: body.lat,
lng: body.lng,
arrivalDate: body.arrivalDate ? new Date(body.arrivalDate) : null,
departureDate: body.departureDate ? new Date(body.departureDate) : null,
notes: body.notes,
sortOrder: body.sortOrder ?? 0,
},
});
return NextResponse.json(destination, { status: 201 });
} catch (error) {
console.error('Create destination error:', error);
return NextResponse.json({ error: 'Failed to create destination' }, { status: 500 });
}
}

View File

@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const body = await request.json();
const expense = await prisma.expense.create({
data: {
tripId: params.id,
paidById: body.paidById,
description: body.description,
amount: body.amount,
currency: body.currency || 'USD',
category: body.category || 'OTHER',
date: body.date ? new Date(body.date) : null,
splitType: body.splitType || 'EQUAL',
},
});
return NextResponse.json(expense, { status: 201 });
} catch (error) {
console.error('Create expense error:', error);
return NextResponse.json({ error: 'Failed to create expense' }, { status: 500 });
}
}

View File

@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const body = await request.json();
const item = await prisma.itineraryItem.create({
data: {
tripId: params.id,
destinationId: body.destinationId,
title: body.title,
description: body.description,
date: body.date ? new Date(body.date) : null,
startTime: body.startTime,
endTime: body.endTime,
category: body.category || 'ACTIVITY',
sortOrder: body.sortOrder ?? 0,
},
});
return NextResponse.json(item, { status: 201 });
} catch (error) {
console.error('Create itinerary item error:', error);
return NextResponse.json({ error: 'Failed to create itinerary item' }, { status: 500 });
}
}

View File

@ -0,0 +1,25 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const body = await request.json();
const item = await prisma.packingItem.create({
data: {
tripId: params.id,
addedById: body.addedById,
name: body.name,
category: body.category,
quantity: body.quantity ?? 1,
sortOrder: body.sortOrder ?? 0,
},
});
return NextResponse.json(item, { status: 201 });
} catch (error) {
console.error('Create packing item error:', error);
return NextResponse.json({ error: 'Failed to create packing item' }, { status: 500 });
}
}

View File

@ -0,0 +1,78 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function GET(
_request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const trip = await prisma.trip.findUnique({
where: { id: params.id },
include: {
destinations: { orderBy: { sortOrder: 'asc' } },
itineraryItems: { orderBy: [{ date: 'asc' }, { sortOrder: 'asc' }] },
bookings: { orderBy: { startDate: 'asc' } },
expenses: { orderBy: { date: 'desc' } },
packingItems: { orderBy: [{ category: 'asc' }, { sortOrder: 'asc' }] },
collaborators: { include: { user: true } },
},
});
if (!trip) {
return NextResponse.json({ error: 'Trip not found' }, { status: 404 });
}
return NextResponse.json(trip);
} catch (error) {
console.error('Get trip error:', error);
return NextResponse.json(
{ error: 'Failed to get trip' },
{ status: 500 }
);
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const body = await request.json();
const trip = await prisma.trip.update({
where: { id: params.id },
data: {
title: body.title,
description: body.description,
startDate: body.startDate ? new Date(body.startDate) : undefined,
endDate: body.endDate ? new Date(body.endDate) : undefined,
budgetTotal: body.budgetTotal,
budgetCurrency: body.budgetCurrency,
status: body.status,
},
});
return NextResponse.json(trip);
} catch (error) {
console.error('Update trip error:', error);
return NextResponse.json(
{ error: 'Failed to update trip' },
{ status: 500 }
);
}
}
export async function DELETE(
_request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
await prisma.trip.delete({ where: { id: params.id } });
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Delete trip error:', error);
return NextResponse.json(
{ error: 'Failed to delete trip' },
{ status: 500 }
);
}
}

View File

@ -0,0 +1,24 @@
import { NextRequest, NextResponse } from 'next/server';
import { parseTrip } from '@/lib/gemini';
export async function POST(request: NextRequest) {
try {
const { text } = await request.json();
if (!text || typeof text !== 'string' || text.trim().length === 0) {
return NextResponse.json(
{ error: 'Please provide a trip description' },
{ status: 400 }
);
}
const parsed = await parseTrip(text.trim());
return NextResponse.json(parsed);
} catch (error) {
console.error('Parse error:', error);
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Failed to parse trip' },
{ status: 500 }
);
}
}

132
src/app/api/trips/route.ts Normal file
View File

@ -0,0 +1,132 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { generateSlug } from '@/lib/slug';
import { ParsedTrip } from '@/lib/types';
export async function GET() {
try {
const trips = await prisma.trip.findMany({
include: {
destinations: { orderBy: { sortOrder: 'asc' } },
collaborators: { include: { user: true } },
_count: {
select: {
itineraryItems: true,
bookings: true,
expenses: true,
packingItems: true,
},
},
},
orderBy: { updatedAt: 'desc' },
});
return NextResponse.json(trips);
} catch (error) {
console.error('List trips error:', error);
return NextResponse.json(
{ error: 'Failed to list trips' },
{ status: 500 }
);
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { parsed, rawInput }: { parsed: ParsedTrip; rawInput: string } = body;
if (!parsed?.title) {
return NextResponse.json(
{ error: 'Trip title is required' },
{ status: 400 }
);
}
// Generate unique slug
let slug = generateSlug(parsed.title);
const existing = await prisma.trip.findUnique({ where: { slug } });
if (existing) {
slug = `${slug}-${Date.now().toString(36)}`;
}
// Create trip with all related entities in a transaction
const trip = await prisma.$transaction(async (tx) => {
const newTrip = await tx.trip.create({
data: {
title: parsed.title,
slug,
description: parsed.destinations.map(d => d.name).join(' → '),
rawInput: rawInput || null,
startDate: parsed.startDate ? new Date(parsed.startDate) : null,
endDate: parsed.endDate ? new Date(parsed.endDate) : null,
budgetTotal: parsed.budgetTotal,
budgetCurrency: parsed.budgetCurrency || 'USD',
status: 'PLANNING',
},
});
// Create destinations
if (parsed.destinations.length > 0) {
await tx.destination.createMany({
data: parsed.destinations.map((d, i) => ({
tripId: newTrip.id,
name: d.name,
country: d.country,
arrivalDate: d.arrivalDate ? new Date(d.arrivalDate) : null,
departureDate: d.departureDate ? new Date(d.departureDate) : null,
sortOrder: i,
})),
});
}
// Create itinerary items
if (parsed.itineraryItems.length > 0) {
await tx.itineraryItem.createMany({
data: parsed.itineraryItems.map((item, i) => ({
tripId: newTrip.id,
title: item.title,
category: item.category as never,
date: item.date ? new Date(item.date) : null,
description: item.description,
sortOrder: i,
})),
});
}
// Create bookings
if (parsed.bookings.length > 0) {
await tx.booking.createMany({
data: parsed.bookings.map((b) => ({
tripId: newTrip.id,
type: b.type as never,
provider: b.provider,
details: b.details,
cost: b.cost,
status: 'PLANNED',
})),
});
}
return newTrip;
});
// Re-fetch with relations
const fullTrip = await prisma.trip.findUnique({
where: { id: trip.id },
include: {
destinations: { orderBy: { sortOrder: 'asc' } },
itineraryItems: { orderBy: { sortOrder: 'asc' } },
bookings: true,
},
});
return NextResponse.json(fullTrip, { status: 201 });
} catch (error) {
console.error('Create trip error:', error);
return NextResponse.json(
{ error: 'Failed to create trip' },
{ status: 500 }
);
}
}

13
src/app/globals.css Normal file
View File

@ -0,0 +1,13 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
body {
color: var(--foreground);
background: var(--background);
}

33
src/app/layout.tsx Normal file
View File

@ -0,0 +1,33 @@
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
const inter = Inter({
subsets: ['latin'],
variable: '--font-inter',
})
export const metadata: Metadata = {
title: 'rTrips - Collaborative Trip Planning',
description: 'Plan trips together with natural language input, structured itineraries, and a real-time collaborative canvas. Describe your trip and let AI structure it for you.',
openGraph: {
title: 'rTrips - Collaborative Trip Planning',
description: 'Plan trips together with natural language input and real-time collaborative canvas.',
type: 'website',
url: 'https://rtrips.online',
},
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body className={`${inter.variable} font-sans antialiased`}>
{children}
</body>
</html>
)
}

138
src/app/page.tsx Normal file
View File

@ -0,0 +1,138 @@
import Link from 'next/link'
export default function Home() {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white">
{/* Nav */}
<nav className="border-b border-slate-700/50 backdrop-blur-sm">
<div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="w-8 h-8 bg-gradient-to-br from-teal-400 to-cyan-500 rounded-lg flex items-center justify-center font-bold text-slate-900 text-sm">
rT
</div>
<span className="font-semibold text-lg">rTrips</span>
</div>
<div className="flex items-center gap-4">
<Link
href="/trips"
className="text-sm text-slate-300 hover:text-white transition-colors"
>
My Trips
</Link>
<Link
href="/trips/new"
className="text-sm px-4 py-2 bg-teal-600 hover:bg-teal-500 rounded-lg transition-colors font-medium"
>
Plan a Trip
</Link>
</div>
</div>
</nav>
{/* Hero */}
<section className="max-w-6xl mx-auto px-6 pt-20 pb-16">
<div className="text-center max-w-3xl mx-auto">
<h1 className="text-5xl font-bold mb-6 bg-gradient-to-r from-teal-300 via-cyan-300 to-blue-300 bg-clip-text text-transparent">
Plan Your Trip, Naturally
</h1>
<p className="text-xl text-slate-300 mb-8 leading-relaxed">
Describe your dream trip in plain language. We&apos;ll structure it into
itineraries, budgets, and bookings &mdash; then give you a collaborative
canvas to plan together in real-time.
</p>
<div className="flex items-center justify-center gap-4">
<Link
href="/trips/new"
className="px-6 py-3 bg-teal-600 hover:bg-teal-500 rounded-xl text-lg font-medium transition-all shadow-lg shadow-teal-900/30"
>
Start Planning
</Link>
<Link
href="/trips"
className="px-6 py-3 bg-slate-700 hover:bg-slate-600 rounded-xl text-lg font-medium transition-all border border-slate-600"
>
My Trips
</Link>
</div>
</div>
</section>
{/* How it Works */}
<section className="max-w-6xl mx-auto px-6 py-16">
<h2 className="text-3xl font-bold text-center mb-12">How It Works</h2>
<div className="grid md:grid-cols-3 gap-8">
{/* Describe */}
<div className="bg-slate-800/50 rounded-2xl p-6 border border-slate-700/50">
<div className="w-12 h-12 bg-teal-500/20 rounded-xl flex items-center justify-center mb-4">
<svg className="w-6 h-6 text-teal-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
</div>
<h3 className="text-lg font-semibold mb-2">Describe It</h3>
<p className="text-slate-400 text-sm leading-relaxed">
Tell us about your trip in natural language. &ldquo;Fly from Toronto to Bali
for 2 weeks in March, budget $3000.&rdquo; We parse it into structured data
you can refine.
</p>
</div>
{/* Structure */}
<div className="bg-slate-800/50 rounded-2xl p-6 border border-slate-700/50">
<div className="w-12 h-12 bg-cyan-500/20 rounded-xl flex items-center justify-center mb-4">
<svg className="w-6 h-6 text-cyan-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
</svg>
</div>
<h3 className="text-lg font-semibold mb-2">We Structure It</h3>
<p className="text-slate-400 text-sm leading-relaxed">
AI extracts destinations, dates, budgets, and bookings into organized views.
Edit itineraries, track expenses, manage packing lists &mdash; all structured
and searchable.
</p>
</div>
{/* Collaborate */}
<div className="bg-slate-800/50 rounded-2xl p-6 border border-slate-700/50">
<div className="w-12 h-12 bg-blue-500/20 rounded-xl flex items-center justify-center mb-4">
<svg className="w-6 h-6 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
</div>
<h3 className="text-lg font-semibold mb-2">Collaborate on Canvas</h3>
<p className="text-slate-400 text-sm leading-relaxed">
Open the collaborative canvas to plan visually with your travel partners.
Drag destinations, connect itineraries, and brainstorm together in real-time
or async.
</p>
</div>
</div>
</section>
{/* CTA */}
<section className="max-w-6xl mx-auto px-6 py-16 text-center">
<h2 className="text-3xl font-bold mb-4">Ready to plan your next adventure?</h2>
<p className="text-slate-400 mb-8 max-w-lg mx-auto">
Just describe where you want to go. We&apos;ll handle the rest.
</p>
<Link
href="/trips/new"
className="inline-block px-8 py-4 bg-teal-600 hover:bg-teal-500 rounded-xl text-lg font-medium transition-all shadow-lg shadow-teal-900/30"
>
Plan a Trip
</Link>
</section>
{/* Footer */}
<footer className="border-t border-slate-700/50 py-8">
<div className="max-w-6xl mx-auto px-6 flex items-center justify-between text-sm text-slate-500">
<span>rTrips.online</span>
<div className="flex items-center gap-6">
<Link href="/trips/new" className="hover:text-slate-300 transition-colors">Plan a Trip</Link>
<Link href="/trips" className="hover:text-slate-300 transition-colors">My Trips</Link>
<a href="https://rspace.online" className="hover:text-slate-300 transition-colors">rSpace</a>
</div>
</div>
</footer>
</div>
)
}

View File

@ -0,0 +1,66 @@
'use client';
import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { CanvasEmbed } from '@/components/CanvasEmbed';
export default function FullScreenCanvas() {
const params = useParams();
const router = useRouter();
const [canvasSlug, setCanvasSlug] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(`/api/trips/${params.id}`)
.then((res) => res.json())
.then((trip) => setCanvasSlug(trip.canvasSlug))
.catch(console.error)
.finally(() => setLoading(false));
}, [params.id]);
if (loading) {
return (
<div className="h-screen bg-slate-900 flex items-center justify-center">
<svg className="animate-spin h-8 w-8 text-teal-400" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<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" />
</svg>
</div>
);
}
if (!canvasSlug) {
return (
<div className="h-screen bg-slate-900 flex items-center justify-center text-white">
<div className="text-center">
<p className="text-slate-400 mb-4">No canvas linked to this trip yet.</p>
<button
onClick={() => router.back()}
className="text-teal-400 hover:text-teal-300"
>
Back to Trip
</button>
</div>
</div>
);
}
return (
<div className="h-screen bg-slate-900 relative">
{/* Floating back button */}
<div className="absolute top-4 left-4 z-20">
<button
onClick={() => router.push(`/trips/${params.id}`)}
className="px-4 py-2 bg-slate-800/90 hover:bg-slate-700 border border-slate-600/50 rounded-lg text-sm text-white backdrop-blur-sm transition-colors flex items-center gap-2"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
Back to Trip
</button>
</div>
<CanvasEmbed canvasSlug={canvasSlug} className="h-full w-full" />
</div>
);
}

462
src/app/trips/[id]/page.tsx Normal file
View File

@ -0,0 +1,462 @@
'use client';
import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { format } from 'date-fns';
import { CanvasEmbed } from '@/components/CanvasEmbed';
interface Trip {
id: string;
title: string;
slug: string;
description: string | null;
startDate: string | null;
endDate: string | null;
budgetTotal: number | null;
budgetCurrency: string;
status: string;
canvasSlug: string | null;
destinations: Destination[];
itineraryItems: ItineraryItem[];
bookings: Booking[];
expenses: Expense[];
packingItems: PackingItem[];
}
interface Destination {
id: string;
name: string;
country: string | null;
arrivalDate: string | null;
departureDate: string | null;
notes: string | null;
}
interface ItineraryItem {
id: string;
title: string;
description: string | null;
date: string | null;
startTime: string | null;
endTime: string | null;
category: string;
}
interface Booking {
id: string;
type: string;
provider: string | null;
confirmationNumber: string | null;
details: string | null;
cost: number | null;
currency: string;
startDate: string | null;
endDate: string | null;
status: string;
}
interface Expense {
id: string;
description: string;
amount: number;
currency: string;
category: string;
date: string | null;
}
interface PackingItem {
id: string;
name: string;
category: string | null;
packed: boolean;
quantity: number;
}
type Tab = 'overview' | 'itinerary' | 'destinations' | 'bookings' | 'budget' | 'packing';
const TABS: { key: Tab; label: string }[] = [
{ key: 'overview', label: 'Overview' },
{ key: 'itinerary', label: 'Itinerary' },
{ key: 'destinations', label: 'Destinations' },
{ key: 'bookings', label: 'Bookings' },
{ key: 'budget', label: 'Budget' },
{ key: 'packing', label: 'Packing' },
];
const CATEGORY_ICONS: Record<string, string> = {
FLIGHT: '\u2708\uFE0F',
TRANSPORT: '\uD83D\uDE8C',
ACCOMMODATION: '\uD83C\uDFE8',
ACTIVITY: '\uD83C\uDFAF',
MEAL: '\uD83C\uDF7D\uFE0F',
FREE_TIME: '\u2600\uFE0F',
OTHER: '\uD83D\uDCCC',
};
const BOOKING_TYPE_COLORS: Record<string, string> = {
FLIGHT: 'bg-blue-500/20 text-blue-300',
HOTEL: 'bg-purple-500/20 text-purple-300',
CAR_RENTAL: 'bg-amber-500/20 text-amber-300',
ACTIVITY: 'bg-teal-500/20 text-teal-300',
RESTAURANT: 'bg-orange-500/20 text-orange-300',
OTHER: 'bg-slate-500/20 text-slate-300',
};
const STATUS_BADGES: Record<string, string> = {
PLANNED: 'bg-slate-500/20 text-slate-300',
BOOKED: 'bg-blue-500/20 text-blue-300',
CONFIRMED: 'bg-emerald-500/20 text-emerald-300',
CANCELLED: 'bg-red-500/20 text-red-300',
};
export default function TripDashboard() {
const params = useParams();
const [trip, setTrip] = useState<Trip | null>(null);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<Tab>('overview');
const [showCanvas, setShowCanvas] = useState(false);
useEffect(() => {
fetch(`/api/trips/${params.id}`)
.then((res) => res.json())
.then(setTrip)
.catch(console.error)
.finally(() => setLoading(false));
}, [params.id]);
if (loading) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center">
<svg className="animate-spin h-8 w-8 text-teal-400" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<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" />
</svg>
</div>
);
}
if (!trip) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white flex items-center justify-center">
<div className="text-center">
<p className="text-slate-400 mb-4">Trip not found</p>
<Link href="/trips" className="text-teal-400 hover:text-teal-300">Back to My Trips</Link>
</div>
</div>
);
}
const totalExpenses = trip.expenses.reduce((sum, e) => sum + e.amount, 0);
const packedCount = trip.packingItems.filter((i) => i.packed).length;
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white">
{/* Nav */}
<nav className="border-b border-slate-700/50 backdrop-blur-sm">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link href="/" className="flex items-center gap-2">
<div className="w-8 h-8 bg-gradient-to-br from-teal-400 to-cyan-500 rounded-lg flex items-center justify-center font-bold text-slate-900 text-sm">
rT
</div>
</Link>
<span className="text-slate-600">/</span>
<Link href="/trips" className="text-sm text-slate-400 hover:text-white transition-colors">
Trips
</Link>
<span className="text-slate-600">/</span>
<span className="text-sm font-medium">{trip.title}</span>
</div>
<button
onClick={() => setShowCanvas(!showCanvas)}
className="text-sm px-4 py-2 bg-slate-700 hover:bg-slate-600 border border-slate-600 rounded-lg transition-colors"
>
{showCanvas ? 'Hide Canvas' : 'Show Canvas'}
</button>
</div>
</nav>
<div className="max-w-7xl mx-auto px-6 py-6">
<div className={`flex gap-6 ${showCanvas ? '' : ''}`}>
{/* Main content */}
<div className={`${showCanvas ? 'w-3/5' : 'w-full'} space-y-6`}>
{/* Header */}
<div className="bg-slate-800/50 rounded-xl p-6 border border-slate-700/50">
<div className="flex items-start justify-between mb-4">
<div>
<h1 className="text-2xl font-bold">{trip.title}</h1>
{trip.description && <p className="text-slate-400 mt-1">{trip.description}</p>}
</div>
<span className={`text-xs px-2 py-1 rounded-full ${STATUS_BADGES[trip.status] || STATUS_BADGES.PLANNED}`}>
{trip.status.replace('_', ' ')}
</span>
</div>
<div className="flex items-center gap-6 text-sm text-slate-400">
{trip.startDate && (
<span>{format(new Date(trip.startDate), 'MMM d')} &ndash; {trip.endDate ? format(new Date(trip.endDate), 'MMM d, yyyy') : '...'}</span>
)}
{trip.budgetTotal && (
<span>Budget: {trip.budgetCurrency} {trip.budgetTotal.toLocaleString()}</span>
)}
<span>{trip.destinations.length} destinations</span>
</div>
</div>
{/* Tabs */}
<div className="flex gap-1 bg-slate-800/30 rounded-lg p-1">
{TABS.map((tab) => (
<button
key={tab.key}
onClick={() => setActiveTab(tab.key)}
className={`flex-1 py-2 px-3 rounded-md text-sm font-medium transition-all ${
activeTab === tab.key
? 'bg-slate-700 text-white'
: 'text-slate-400 hover:text-white hover:bg-slate-700/50'
}`}
>
{tab.label}
</button>
))}
</div>
{/* Tab Content */}
<div className="space-y-4">
{activeTab === 'overview' && (
<div className="grid grid-cols-2 gap-4">
<div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700/50">
<h3 className="text-sm font-medium text-slate-400 mb-3">Destinations</h3>
{trip.destinations.map((d) => (
<div key={d.id} className="flex items-center gap-2 mb-2">
<div className="w-2 h-2 bg-teal-400 rounded-full" />
<span>{d.name}</span>
{d.country && <span className="text-xs text-slate-500">({d.country})</span>}
</div>
))}
</div>
<div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700/50">
<h3 className="text-sm font-medium text-slate-400 mb-3">Budget</h3>
{trip.budgetTotal && (
<>
<div className="flex justify-between text-sm mb-2">
<span>Spent</span>
<span>{trip.budgetCurrency} {totalExpenses.toLocaleString()} / {trip.budgetTotal.toLocaleString()}</span>
</div>
<div className="w-full h-2 bg-slate-700 rounded-full overflow-hidden">
<div
className="h-full bg-teal-500 rounded-full transition-all"
style={{ width: `${Math.min((totalExpenses / trip.budgetTotal) * 100, 100)}%` }}
/>
</div>
</>
)}
</div>
<div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700/50">
<h3 className="text-sm font-medium text-slate-400 mb-3">Bookings</h3>
<p className="text-2xl font-bold">{trip.bookings.length}</p>
<p className="text-xs text-slate-500">{trip.bookings.filter(b => b.status === 'CONFIRMED').length} confirmed</p>
</div>
<div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700/50">
<h3 className="text-sm font-medium text-slate-400 mb-3">Packing</h3>
<p className="text-2xl font-bold">{packedCount}/{trip.packingItems.length}</p>
<p className="text-xs text-slate-500">items packed</p>
</div>
</div>
)}
{activeTab === 'itinerary' && (
<div className="space-y-3">
{trip.itineraryItems.length === 0 ? (
<p className="text-slate-500 text-center py-8">No itinerary items yet</p>
) : (
trip.itineraryItems.map((item) => (
<div key={item.id} className="bg-slate-800/50 rounded-lg p-4 border border-slate-700/50 flex items-start gap-3">
<span className="text-lg">{CATEGORY_ICONS[item.category] || CATEGORY_ICONS.OTHER}</span>
<div className="flex-1">
<p className="font-medium">{item.title}</p>
{item.description && <p className="text-sm text-slate-400 mt-0.5">{item.description}</p>}
<div className="flex gap-3 mt-1 text-xs text-slate-500">
{item.date && <span>{format(new Date(item.date), 'MMM d, yyyy')}</span>}
{item.startTime && <span>{item.startTime}{item.endTime && ` - ${item.endTime}`}</span>}
</div>
</div>
<span className="text-xs bg-slate-700 text-slate-300 rounded px-1.5 py-0.5">{item.category}</span>
</div>
))
)}
</div>
)}
{activeTab === 'destinations' && (
<div className="space-y-3">
{trip.destinations.map((dest, i) => (
<div key={dest.id} className="bg-slate-800/50 rounded-xl p-5 border border-slate-700/50">
<div className="flex items-start gap-4">
<div className="w-10 h-10 bg-teal-500/20 rounded-lg flex items-center justify-center text-teal-400 font-bold">
{i + 1}
</div>
<div className="flex-1">
<h3 className="font-semibold text-lg">{dest.name}</h3>
{dest.country && <p className="text-sm text-slate-400">{dest.country}</p>}
{(dest.arrivalDate || dest.departureDate) && (
<p className="text-xs text-slate-500 mt-1">
{dest.arrivalDate && format(new Date(dest.arrivalDate), 'MMM d')}
{dest.arrivalDate && dest.departureDate && ' \u2192 '}
{dest.departureDate && format(new Date(dest.departureDate), 'MMM d, yyyy')}
</p>
)}
{dest.notes && <p className="text-sm text-slate-400 mt-2">{dest.notes}</p>}
</div>
</div>
</div>
))}
</div>
)}
{activeTab === 'bookings' && (
<div className="space-y-3">
{trip.bookings.length === 0 ? (
<p className="text-slate-500 text-center py-8">No bookings yet</p>
) : (
trip.bookings.map((b) => (
<div key={b.id} className="bg-slate-800/50 rounded-lg p-4 border border-slate-700/50">
<div className="flex items-start justify-between">
<div className="flex items-center gap-2">
<span className={`text-xs px-2 py-0.5 rounded ${BOOKING_TYPE_COLORS[b.type] || BOOKING_TYPE_COLORS.OTHER}`}>
{b.type}
</span>
<span className="font-medium">{b.provider || b.details || 'TBD'}</span>
</div>
<div className="flex items-center gap-2">
{b.cost && <span className="text-sm text-slate-300">{b.currency} {b.cost.toLocaleString()}</span>}
<span className={`text-xs px-1.5 py-0.5 rounded ${STATUS_BADGES[b.status] || STATUS_BADGES.PLANNED}`}>
{b.status}
</span>
</div>
</div>
{b.confirmationNumber && (
<p className="text-xs text-slate-500 mt-1">Confirmation: {b.confirmationNumber}</p>
)}
{b.details && b.provider && (
<p className="text-sm text-slate-400 mt-1">{b.details}</p>
)}
</div>
))
)}
</div>
)}
{activeTab === 'budget' && (
<div className="space-y-4">
{trip.budgetTotal && (
<div className="bg-slate-800/50 rounded-xl p-5 border border-slate-700/50">
<div className="flex justify-between mb-3">
<span className="text-slate-400">Total Budget</span>
<span className="font-semibold">{trip.budgetCurrency} {trip.budgetTotal.toLocaleString()}</span>
</div>
<div className="flex justify-between mb-2 text-sm">
<span className="text-slate-400">Spent</span>
<span className="text-teal-400">{trip.budgetCurrency} {totalExpenses.toLocaleString()}</span>
</div>
<div className="w-full h-3 bg-slate-700 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all ${
totalExpenses / trip.budgetTotal > 0.9 ? 'bg-red-500' : 'bg-teal-500'
}`}
style={{ width: `${Math.min((totalExpenses / trip.budgetTotal) * 100, 100)}%` }}
/>
</div>
<p className="text-xs text-slate-500 mt-2">
{trip.budgetCurrency} {(trip.budgetTotal - totalExpenses).toLocaleString()} remaining
</p>
</div>
)}
<div className="space-y-2">
{trip.expenses.length === 0 ? (
<p className="text-slate-500 text-center py-8">No expenses tracked yet</p>
) : (
trip.expenses.map((e) => (
<div key={e.id} className="flex items-center justify-between bg-slate-800/50 rounded-lg px-4 py-3 border border-slate-700/50">
<div>
<p className="text-sm font-medium">{e.description}</p>
<p className="text-xs text-slate-500">{e.category} {e.date && `\u00B7 ${format(new Date(e.date), 'MMM d')}`}</p>
</div>
<span className="font-medium">{e.currency} {e.amount.toLocaleString()}</span>
</div>
))
)}
</div>
</div>
)}
{activeTab === 'packing' && (
<div className="space-y-2">
{trip.packingItems.length === 0 ? (
<p className="text-slate-500 text-center py-8">No packing items yet</p>
) : (
<>
<div className="flex justify-between text-sm text-slate-400 mb-3">
<span>{packedCount} of {trip.packingItems.length} packed</span>
<div className="w-32 h-2 bg-slate-700 rounded-full overflow-hidden mt-1">
<div
className="h-full bg-emerald-500 rounded-full"
style={{ width: `${trip.packingItems.length > 0 ? (packedCount / trip.packingItems.length) * 100 : 0}%` }}
/>
</div>
</div>
{trip.packingItems.map((item) => (
<div key={item.id} className="flex items-center gap-3 bg-slate-800/50 rounded-lg px-4 py-2.5 border border-slate-700/50">
<input
type="checkbox"
checked={item.packed}
readOnly
className="w-4 h-4 rounded border-slate-600 bg-slate-700 text-teal-500"
/>
<span className={item.packed ? 'line-through text-slate-500' : ''}>{item.name}</span>
{item.quantity > 1 && <span className="text-xs text-slate-500">x{item.quantity}</span>}
{item.category && <span className="text-xs bg-slate-700 text-slate-400 rounded px-1.5 py-0.5 ml-auto">{item.category}</span>}
</div>
))}
</>
)}
</div>
)}
</div>
</div>
{/* Canvas sidebar */}
{showCanvas && trip.canvasSlug && (
<div className="w-2/5">
<div className="sticky top-6">
<div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-medium text-slate-400">Collaborative Canvas</h3>
<Link
href={`/trips/${trip.id}/canvas`}
className="text-xs text-teal-400 hover:text-teal-300"
>
Full Screen
</Link>
</div>
<CanvasEmbed
canvasSlug={trip.canvasSlug}
className="h-[600px]"
/>
</div>
</div>
)}
{showCanvas && !trip.canvasSlug && (
<div className="w-2/5">
<div className="sticky top-6 bg-slate-800/50 rounded-xl p-6 border border-slate-700/50 text-center">
<p className="text-slate-400 mb-4">No canvas linked yet.</p>
<p className="text-xs text-slate-500">
A collaborative canvas will be created on rSpace when you&apos;re ready to plan visually with your travel partners.
</p>
</div>
</div>
)}
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,90 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { NLInput } from '@/components/NLInput';
import { ParsedTripPreview } from '@/components/ParsedTripPreview';
import { ParsedTrip } from '@/lib/types';
export default function NewTrip() {
const router = useRouter();
const [parsed, setParsed] = useState<ParsedTrip | null>(null);
const [rawInput, setRawInput] = useState('');
const [creating, setCreating] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleParsed = (data: ParsedTrip, raw: string) => {
setParsed(data);
setRawInput(raw);
};
const handleConfirm = async (finalParsed: ParsedTrip) => {
setCreating(true);
setError(null);
try {
const res = await fetch('/api/trips', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ parsed: finalParsed, rawInput }),
});
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || 'Failed to create trip');
}
const trip = await res.json();
router.push(`/trips/${trip.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : 'Something went wrong');
setCreating(false);
}
};
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white">
{/* Nav */}
<nav className="border-b border-slate-700/50 backdrop-blur-sm">
<div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
<Link href="/" className="flex items-center gap-2">
<div className="w-8 h-8 bg-gradient-to-br from-teal-400 to-cyan-500 rounded-lg flex items-center justify-center font-bold text-slate-900 text-sm">
rT
</div>
<span className="font-semibold text-lg">rTrips</span>
</Link>
<Link href="/trips" className="text-sm text-slate-300 hover:text-white transition-colors">
My Trips
</Link>
</div>
</nav>
{/* Content */}
<div className="max-w-2xl mx-auto px-6 py-12">
<h1 className="text-3xl font-bold mb-2">Plan a New Trip</h1>
<p className="text-slate-400 mb-8">
Describe your trip in natural language and we&apos;ll structure it for you.
</p>
{error && (
<div className="mb-6 p-3 bg-red-900/30 border border-red-700/50 rounded-lg text-red-300 text-sm">
{error}
</div>
)}
{!parsed ? (
<NLInput onParsed={handleParsed} />
) : (
<ParsedTripPreview
parsed={parsed}
rawInput={rawInput}
onConfirm={handleConfirm}
onBack={() => setParsed(null)}
loading={creating}
/>
)}
</div>
</div>
);
}

126
src/app/trips/page.tsx Normal file
View File

@ -0,0 +1,126 @@
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { format } from 'date-fns';
interface TripSummary {
id: string;
title: string;
slug: string;
description: string | null;
startDate: string | null;
endDate: string | null;
budgetTotal: number | null;
budgetCurrency: string;
status: string;
destinations: { name: string; country: string | null }[];
_count: {
itineraryItems: number;
bookings: number;
expenses: number;
packingItems: number;
};
updatedAt: string;
}
const STATUS_COLORS: Record<string, string> = {
PLANNING: 'bg-teal-500/20 text-teal-300',
BOOKED: 'bg-blue-500/20 text-blue-300',
IN_PROGRESS: 'bg-amber-500/20 text-amber-300',
COMPLETED: 'bg-emerald-500/20 text-emerald-300',
CANCELLED: 'bg-slate-500/20 text-slate-400',
};
export default function TripsPage() {
const [trips, setTrips] = useState<TripSummary[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/trips')
.then((res) => res.json())
.then(setTrips)
.catch(console.error)
.finally(() => setLoading(false));
}, []);
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white">
{/* Nav */}
<nav className="border-b border-slate-700/50 backdrop-blur-sm">
<div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
<Link href="/" className="flex items-center gap-2">
<div className="w-8 h-8 bg-gradient-to-br from-teal-400 to-cyan-500 rounded-lg flex items-center justify-center font-bold text-slate-900 text-sm">
rT
</div>
<span className="font-semibold text-lg">rTrips</span>
</Link>
<Link
href="/trips/new"
className="text-sm px-4 py-2 bg-teal-600 hover:bg-teal-500 rounded-lg transition-colors font-medium"
>
Plan a Trip
</Link>
</div>
</nav>
<div className="max-w-4xl mx-auto px-6 py-12">
<h1 className="text-3xl font-bold mb-8">My Trips</h1>
{loading ? (
<div className="flex items-center justify-center py-20">
<svg className="animate-spin h-8 w-8 text-teal-400" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<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" />
</svg>
</div>
) : trips.length === 0 ? (
<div className="text-center py-20">
<p className="text-slate-400 mb-4">No trips yet. Start planning your first adventure!</p>
<Link
href="/trips/new"
className="inline-block px-6 py-3 bg-teal-600 hover:bg-teal-500 rounded-xl font-medium transition-all"
>
Plan a Trip
</Link>
</div>
) : (
<div className="space-y-4">
{trips.map((trip) => (
<Link
key={trip.id}
href={`/trips/${trip.id}`}
className="block bg-slate-800/50 rounded-xl p-5 border border-slate-700/50 hover:border-teal-500/30 transition-all group"
>
<div className="flex items-start justify-between mb-3">
<div>
<h2 className="text-lg font-semibold group-hover:text-teal-300 transition-colors">{trip.title}</h2>
{trip.destinations.length > 0 && (
<p className="text-sm text-slate-400 mt-0.5">
{trip.destinations.map((d) => d.name).join(' → ')}
</p>
)}
</div>
<span className={`text-xs px-2 py-1 rounded-full ${STATUS_COLORS[trip.status] || STATUS_COLORS.PLANNING}`}>
{trip.status.replace('_', ' ')}
</span>
</div>
<div className="flex items-center gap-4 text-xs text-slate-500">
{trip.startDate && (
<span>{format(new Date(trip.startDate), 'MMM d, yyyy')}</span>
)}
{trip.budgetTotal && (
<span>{trip.budgetCurrency} {trip.budgetTotal.toLocaleString()}</span>
)}
<span>{trip._count.itineraryItems} items</span>
<span>{trip._count.bookings} bookings</span>
</div>
</Link>
))}
</div>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,35 @@
'use client';
interface CanvasEmbedProps {
canvasSlug: string;
className?: string;
}
export function CanvasEmbed({ canvasSlug, className = '' }: CanvasEmbedProps) {
const rspaceUrl = process.env.NEXT_PUBLIC_RSPACE_URL || 'https://rspace.online';
const canvasUrl = `https://${canvasSlug}.rspace.online`;
return (
<div className={`relative bg-slate-900 rounded-xl overflow-hidden border border-slate-700/50 ${className}`}>
{/* Toolbar */}
<div className="absolute top-2 right-2 z-10 flex gap-2">
<a
href={canvasUrl}
target="_blank"
rel="noopener noreferrer"
className="px-3 py-1.5 bg-slate-800/90 hover:bg-slate-700 border border-slate-600/50 rounded-lg text-xs text-slate-300 backdrop-blur-sm transition-colors"
>
Open in rSpace
</a>
</div>
{/* Canvas iframe */}
<iframe
src={canvasUrl}
className="w-full h-full border-0"
allow="clipboard-write"
title="Trip Canvas"
/>
</div>
);
}

View File

@ -0,0 +1,71 @@
'use client';
import { useState } from 'react';
import { ParsedTrip } from '@/lib/types';
interface NLInputProps {
onParsed: (parsed: ParsedTrip, rawInput: string) => void;
}
export function NLInput({ onParsed }: NLInputProps) {
const [text, setText] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleParse = async () => {
if (!text.trim()) return;
setLoading(true);
setError(null);
try {
const res = await fetch('/api/trips/parse', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: text.trim() }),
});
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || 'Failed to parse');
}
const parsed: ParsedTrip = await res.json();
onParsed(parsed, text.trim());
} catch (err) {
setError(err instanceof Error ? err.message : 'Something went wrong');
} finally {
setLoading(false);
}
};
return (
<div className="space-y-4">
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Describe your trip... (e.g., 'Fly from Toronto to Bali for 2 weeks in March 2026, budget $3000. Want to visit Ubud temples and Seminyak beaches. Need a hotel in each area.')"
className="w-full h-40 bg-slate-800/50 border border-slate-700/50 rounded-xl p-4 text-white placeholder-slate-500 resize-none focus:outline-none focus:ring-2 focus:ring-teal-500/50 focus:border-teal-500/50"
/>
{error && (
<p className="text-red-400 text-sm">{error}</p>
)}
<button
onClick={handleParse}
disabled={loading || !text.trim()}
className="w-full py-3 bg-teal-600 hover:bg-teal-500 disabled:bg-slate-700 disabled:text-slate-500 rounded-xl font-medium transition-all flex items-center justify-center gap-2"
>
{loading ? (
<>
<svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<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" />
</svg>
Parsing your trip...
</>
) : (
'Parse Trip'
)}
</button>
</div>
);
}

View File

@ -0,0 +1,152 @@
'use client';
import { useState } from 'react';
import { ParsedTrip } from '@/lib/types';
interface ParsedTripPreviewProps {
parsed: ParsedTrip;
rawInput: string;
onConfirm: (parsed: ParsedTrip) => void;
onBack: () => void;
loading?: boolean;
}
export function ParsedTripPreview({ parsed, rawInput, onConfirm, onBack, loading }: ParsedTripPreviewProps) {
const [edited, setEdited] = useState<ParsedTrip>(parsed);
return (
<div className="space-y-6">
{/* Raw input reference */}
<div className="bg-slate-800/30 rounded-lg p-3 border border-slate-700/30">
<p className="text-xs text-slate-500 mb-1">Your description:</p>
<p className="text-sm text-slate-400 italic">&ldquo;{rawInput}&rdquo;</p>
</div>
{/* Title */}
<div>
<label className="block text-sm text-slate-400 mb-1">Trip Title</label>
<input
type="text"
value={edited.title}
onChange={(e) => setEdited({ ...edited, title: e.target.value })}
className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-teal-500/50"
/>
</div>
{/* Dates & Budget */}
<div className="grid grid-cols-3 gap-4">
<div>
<label className="block text-sm text-slate-400 mb-1">Start Date</label>
<input
type="date"
value={edited.startDate?.split('T')[0] || ''}
onChange={(e) => setEdited({ ...edited, startDate: e.target.value || null })}
className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-teal-500/50"
/>
</div>
<div>
<label className="block text-sm text-slate-400 mb-1">End Date</label>
<input
type="date"
value={edited.endDate?.split('T')[0] || ''}
onChange={(e) => setEdited({ ...edited, endDate: e.target.value || null })}
className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-teal-500/50"
/>
</div>
<div>
<label className="block text-sm text-slate-400 mb-1">Budget ({edited.budgetCurrency})</label>
<input
type="number"
value={edited.budgetTotal ?? ''}
onChange={(e) => setEdited({ ...edited, budgetTotal: e.target.value ? Number(e.target.value) : null })}
className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-teal-500/50"
/>
</div>
</div>
{/* Destinations */}
{edited.destinations.length > 0 && (
<div>
<h3 className="text-sm font-medium text-slate-300 mb-2">Destinations ({edited.destinations.length})</h3>
<div className="space-y-2">
{edited.destinations.map((dest, i) => (
<div key={i} className="bg-slate-800/50 rounded-lg p-3 border border-slate-700/50 flex items-center gap-3">
<div className="w-8 h-8 bg-teal-500/20 rounded-lg flex items-center justify-center text-teal-400 font-bold text-sm">
{i + 1}
</div>
<div className="flex-1">
<p className="text-white font-medium">{dest.name}</p>
{dest.country && <p className="text-xs text-slate-400">{dest.country}</p>}
</div>
{(dest.arrivalDate || dest.departureDate) && (
<p className="text-xs text-slate-500">
{dest.arrivalDate?.split('T')[0]} {dest.departureDate?.split('T')[0]}
</p>
)}
</div>
))}
</div>
</div>
)}
{/* Itinerary Items */}
{edited.itineraryItems.length > 0 && (
<div>
<h3 className="text-sm font-medium text-slate-300 mb-2">Itinerary ({edited.itineraryItems.length} items)</h3>
<div className="space-y-1">
{edited.itineraryItems.map((item, i) => (
<div key={i} className="flex items-center gap-2 text-sm">
<span className="text-xs bg-slate-700 rounded px-1.5 py-0.5 text-slate-300">{item.category}</span>
<span className="text-white">{item.title}</span>
{item.date && <span className="text-slate-500 text-xs">{item.date.split('T')[0]}</span>}
</div>
))}
</div>
</div>
)}
{/* Bookings */}
{edited.bookings.length > 0 && (
<div>
<h3 className="text-sm font-medium text-slate-300 mb-2">Bookings ({edited.bookings.length})</h3>
<div className="space-y-1">
{edited.bookings.map((booking, i) => (
<div key={i} className="flex items-center gap-2 text-sm">
<span className="text-xs bg-cyan-900/50 text-cyan-300 rounded px-1.5 py-0.5">{booking.type}</span>
<span className="text-white">{booking.details || booking.provider || 'TBD'}</span>
{booking.cost && <span className="text-slate-400">${booking.cost}</span>}
</div>
))}
</div>
</div>
)}
{/* Actions */}
<div className="flex gap-3">
<button
onClick={onBack}
className="flex-1 py-3 bg-slate-700 hover:bg-slate-600 rounded-xl font-medium transition-all"
>
Edit Description
</button>
<button
onClick={() => onConfirm(edited)}
disabled={loading}
className="flex-1 py-3 bg-teal-600 hover:bg-teal-500 disabled:bg-slate-700 rounded-xl font-medium transition-all flex items-center justify-center gap-2"
>
{loading ? (
<>
<svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<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" />
</svg>
Creating...
</>
) : (
'Create Trip'
)}
</button>
</div>
</div>
);
}

106
src/lib/gemini.ts Normal file
View File

@ -0,0 +1,106 @@
import { ParsedTrip } from './types';
const GEMINI_URL = 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions';
const TRIP_PARSER_SYSTEM_PROMPT = `You are a trip planning assistant. Parse the user's trip description into structured JSON.
Output this exact JSON schema:
{
"title": "string - descriptive trip title (e.g. 'Bali Adventure March 2026')",
"destinations": [
{
"name": "string - city or region name",
"country": "string or null",
"arrivalDate": "ISO date string or null",
"departureDate": "ISO date string or null"
}
],
"startDate": "ISO date string or null",
"endDate": "ISO date string or null",
"budgetTotal": "number or null",
"budgetCurrency": "3-letter currency code, default USD",
"travelers": "number or null",
"itineraryItems": [
{
"title": "string",
"category": "FLIGHT | TRANSPORT | ACCOMMODATION | ACTIVITY | MEAL | OTHER",
"date": "ISO date string or null",
"description": "string or null"
}
],
"bookings": [
{
"type": "FLIGHT | HOTEL | CAR_RENTAL | TRAIN | BUS | FERRY | ACTIVITY | RESTAURANT | OTHER",
"provider": "string or null (airline name, hotel chain, etc.)",
"details": "string summarizing the booking",
"cost": "number or null"
}
]
}
Rules:
- Be generous with extraction. If the user says "fly from Toronto to Bali" infer a FLIGHT booking and itinerary item.
- If they say "2 weeks" calculate the end date from the start date.
- If they mention a hotel or accommodation, create both a booking and itinerary item.
- If no specific dates are given, leave date fields as null.
- Always return valid JSON matching the schema above.`;
function extractJSON(text: string): string {
// Handle Gemini's tendency to wrap JSON in ```json fences
const fenceMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/);
if (fenceMatch) return fenceMatch[1].trim();
// Try to find raw JSON object
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (jsonMatch) return jsonMatch[0];
return text;
}
export async function parseTrip(naturalLanguage: string): Promise<ParsedTrip> {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
throw new Error('GEMINI_API_KEY not configured');
}
const response = await fetch(GEMINI_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: 'gemini-2.0-flash',
messages: [
{ role: 'system', content: TRIP_PARSER_SYSTEM_PROMPT },
{ role: 'user', content: naturalLanguage },
],
response_format: { type: 'json_object' },
}),
});
if (!response.ok) {
const err = await response.text();
throw new Error(`Gemini API error: ${response.status} ${err}`);
}
const data = await response.json();
const content = data.choices?.[0]?.message?.content;
if (!content) {
throw new Error('No content in Gemini response');
}
const jsonStr = extractJSON(content);
const parsed: ParsedTrip = JSON.parse(jsonStr);
// Ensure defaults
return {
title: parsed.title || 'Untitled Trip',
destinations: parsed.destinations || [],
startDate: parsed.startDate || null,
endDate: parsed.endDate || null,
budgetTotal: parsed.budgetTotal || null,
budgetCurrency: parsed.budgetCurrency || 'USD',
travelers: parsed.travelers || null,
itineraryItems: parsed.itineraryItems || [],
bookings: parsed.bookings || [],
};
}

13
src/lib/prisma.ts Normal file
View File

@ -0,0 +1,13 @@
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"],
});
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

9
src/lib/slug.ts Normal file
View File

@ -0,0 +1,9 @@
export function generateSlug(title: string): string {
return title
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 60);
}

32
src/lib/types.ts Normal file
View File

@ -0,0 +1,32 @@
export interface ParsedTrip {
title: string;
destinations: ParsedDestination[];
startDate: string | null;
endDate: string | null;
budgetTotal: number | null;
budgetCurrency: string;
travelers: number | null;
itineraryItems: ParsedItineraryItem[];
bookings: ParsedBooking[];
}
export interface ParsedDestination {
name: string;
country: string | null;
arrivalDate: string | null;
departureDate: string | null;
}
export interface ParsedItineraryItem {
title: string;
category: string;
date: string | null;
description: string | null;
}
export interface ParsedBooking {
type: string;
provider: string | null;
details: string | null;
cost: number | null;
}

17
tailwind.config.ts Normal file
View File

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

26
tsconfig.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"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"]
}