Skip to content
Open

main #114

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
261 changes: 153 additions & 108 deletions app/api/projects/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,112 +1,157 @@
export const dynamic = 'force-dynamic'

import { NextRequest, NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/middleware'
import { sql } from '@/lib/db'

export const GET = withAuth(async (request: NextRequest, auth) => {
const id = request.nextUrl.pathname.split('/').pop()

const userRows = await sql<{ id: string }[]>`
SELECT id FROM users WHERE wallet_address = ${auth.walletAddress} LIMIT 1
`
if (!userRows.length) return NextResponse.json({ error: 'User not found' }, { status: 404 })

const projectRows = await sql<any[]>`
SELECT
p.id,
p.client_id,
p.title,
p.description,
p.status,
p.budget_max,
p.currency,
p.deadline,
p.created_at,
c.id AS contract_id,
c.total_amount AS contract_total_amount,
c.escrow_address AS contract_escrow_address,
c.escrow_status AS contract_escrow_status,
c.status AS contract_status,
c.funded_at AS contract_funded_at,
c.funding_tx_hash AS contract_funding_tx_hash,
-- client info
u_client.display_name AS client_display_name,
u_client.username AS client_username,
u_client.avatar_url AS client_avatar_url,
u_client.wallet_address AS client_wallet_address,
-- freelancer info
u_freelancer.display_name AS freelancer_display_name,
u_freelancer.username AS freelancer_username,
u_freelancer.avatar_url AS freelancer_avatar_url,
u_freelancer.wallet_address AS freelancer_wallet_address,
u_freelancer.avg_rating AS freelancer_avg_rating,
u_freelancer.total_reviews AS freelancer_total_reviews
FROM projects p
LEFT JOIN contracts c ON c.project_id = p.id
LEFT JOIN users u_client ON p.client_id = u_client.id
LEFT JOIN users u_freelancer ON c.freelancer_id = u_freelancer.id
WHERE p.id = ${id} AND (p.client_id = ${userRows[0].id} OR c.freelancer_id = ${userRows[0].id})
LIMIT 1
`
if (!projectRows.length) return NextResponse.json({ error: 'Project not found' }, { status: 404 })

const milestones = await sql<{
id: string; title: string; description: string | null; amount: string
currency: string; due_date: string | null; status: string; sort_order: number
}[]>`
SELECT id, title, description, amount, currency, due_date, status, sort_order
FROM milestones WHERE project_id = ${id} ORDER BY sort_order ASC, created_at ASC
`

const project = projectRows[0]
const hasEscrow = !!project.contract_id
const escrowStatus = project.contract_escrow_status
const escrowTotal = project.contract_total_amount ? parseFloat(project.contract_total_amount) : 0

let escrowFundedAmount = 0
if (escrowStatus === 'funded' || escrowStatus === 'partially_released' || escrowStatus === 'fully_released') {
escrowFundedAmount = escrowTotal
// app/api/projects/[id]/route.ts
//
// GET /api/projects/:id — fetch a single project
// PATCH /api/projects/:id — partial update
// DELETE /api/projects/:id — soft/hard delete

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import {
getProjectById,
updateProject,
deleteProject,
type ProjectStatus,
} from "@/lib/projects";

// ─── Shared ID validation ──────────────────────────────────────────────────

const UUIDSchema = z.string().uuid();

function parseId(raw: string): { id: string } | { error: NextResponse } {
const result = UUIDSchema.safeParse(raw);
if (!result.success) {
return {
error: NextResponse.json(
{ error: "Project ID must be a valid UUID" },
{ status: 400 },
),
};
}
return { id: result.data };
}

// ─── PATCH validation schema ───────────────────────────────────────────────

const PROJECT_STATUS = ["open", "in_progress", "completed", "cancelled"] as const;

const UpdateProjectSchema = z
.object({
title: z
.string()
.min(1, "title cannot be empty")
.max(200, "title must be 200 characters or fewer")
.optional(),
description: z
.string()
.max(2000, "description must be 2000 characters or fewer")
.nullable()
.optional(),
budgetUsdc: z
.number()
.positive("budgetUsdc must be a positive number")
.multipleOf(0.0000001, "budgetUsdc supports up to 7 decimal places")
.optional(),
status: z.enum(PROJECT_STATUS).optional(),
milestoneCount: z
.number()
.int("milestoneCount must be an integer")
.min(0)
.optional(),
})
.refine((data) => Object.keys(data).length > 0, {
message: "At least one field must be provided for an update",
});

// ─── Route context type (Next.js 15 App Router) ───────────────────────────

interface RouteContext {
params: Promise<{ id: string }>;
}

// ─── GET /api/projects/:id ─────────────────────────────────────────────────

export async function GET(
_req: NextRequest,
context: RouteContext,
) {
const { id: rawId } = await context.params;
const parsed = parseId(rawId);
if ("error" in parsed) return parsed.error;

try {
const project = await getProjectById(parsed.id);
if (!project) {
return NextResponse.json({ error: "Project not found" }, { status: 404 });
}
return NextResponse.json(project);
} catch (err) {
console.error(`[GET /api/projects/${parsed.id}]`, err);
return NextResponse.json({ error: "Failed to fetch project" }, { status: 500 });
}
}

// ─── PATCH /api/projects/:id ───────────────────────────────────────────────

export async function PATCH(
req: NextRequest,
context: RouteContext,
) {
const { id: rawId } = await context.params;
const idParsed = parseId(rawId);
if ("error" in idParsed) return idParsed.error;

let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json(
{ error: "Request body must be valid JSON" },
{ status: 400 },
);
}

const escrowReleasedAmount = milestones
.filter(m => m.status === 'paid')
.reduce((sum, m) => sum + parseFloat(m.amount), 0)

const responseProject = {
id: project.id,
title: project.title,
description: project.description,
status: project.status,
budget_max: project.budget_max,
currency: project.currency,
deadline: project.deadline,
created_at: project.created_at,
client: {
display_name: project.client_display_name,
username: project.client_username,
avatar_url: project.client_avatar_url,
wallet_address: project.client_wallet_address
},
freelancer: project.freelancer_wallet_address ? {
display_name: project.freelancer_display_name,
username: project.freelancer_username,
avatar_url: project.freelancer_avatar_url,
wallet_address: project.freelancer_wallet_address,
avg_rating: project.freelancer_avg_rating ? parseFloat(project.freelancer_avg_rating) : 0,
total_reviews: project.freelancer_total_reviews ? parseInt(project.freelancer_total_reviews) : 0
} : null,
escrow: hasEscrow ? {
escrow_address: project.contract_escrow_address,
escrow_status: project.contract_escrow_status,
funded_at: project.contract_funded_at,
funding_tx_hash: project.contract_funding_tx_hash,
total_amount: project.contract_total_amount,
funded_amount: escrowFundedAmount,
released_amount: escrowReleasedAmount,
progress_percent: escrowFundedAmount > 0 ? Math.round((escrowReleasedAmount / escrowFundedAmount) * 100) : 0
} : null
const parsed = UpdateProjectSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: "Validation failed", details: parsed.error.flatten().fieldErrors },
{ status: 422 },
);
}

return NextResponse.json({ project: responseProject, milestones })
})
try {
const updated = await updateProject(idParsed.id, {
...parsed.data,
status: parsed.data.status as ProjectStatus | undefined,
description: parsed.data.description ?? undefined,
});
if (!updated) {
return NextResponse.json({ error: "Project not found" }, { status: 404 });
}
return NextResponse.json(updated);
} catch (err) {
console.error(`[PATCH /api/projects/${idParsed.id}]`, err);
return NextResponse.json({ error: "Failed to update project" }, { status: 500 });
}
}

// ─── DELETE /api/projects/:id ──────────────────────────────────────────────

export async function DELETE(
_req: NextRequest,
context: RouteContext,
) {
const { id: rawId } = await context.params;
const parsed = parseId(rawId);
if ("error" in parsed) return parsed.error;

try {
const deleted = await deleteProject(parsed.id);
if (!deleted) {
return NextResponse.json({ error: "Project not found" }, { status: 404 });
}
return new NextResponse(null, { status: 204 });
} catch (err) {
console.error(`[DELETE /api/projects/${parsed.id}]`, err);
return NextResponse.json({ error: "Failed to delete project" }, { status: 500 });
}
}
Loading