Jacksuyu commited on
Commit
60e766b
·
0 Parent(s):

Initial release: Demand Solution Board v0.1

Browse files
.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ node_modules
2
+ .next
3
+ .git
4
+ .gitignore
5
+ .env
6
+ prisma/dev.db
7
+ prisma/dev.db-journal
8
+ npm-debug.log*
9
+ .DS_Store
.env.example ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ DATABASE_URL="file:./dev.db"
2
+ OPENAI_API_KEY=""
3
+ OPENAI_MODEL="gpt-4.1-mini"
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ node_modules
2
+ .next
3
+ .env
4
+ prisma/dev.db
5
+ prisma/dev.db-journal
6
+ .DS_Store
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:20-bookworm-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY package.json package-lock.json ./
6
+ RUN npm ci
7
+
8
+ COPY . .
9
+
10
+ RUN npm run prisma:generate && npm run build
11
+
12
+ ENV NODE_ENV=production
13
+ ENV PORT=7860
14
+
15
+ EXPOSE 7860
16
+
17
+ CMD ["sh", "-lc", "npx prisma db push && npm start -- -H 0.0.0.0 -p 7860"]
README.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Demand Solution Board
3
+ emoji: 📌
4
+ colorFrom: teal
5
+ colorTo: orange
6
+ sdk: docker
7
+ app_port: 7860
8
+ ---
9
+
10
+ # Demand Solution Board (V0.1)
11
+
12
+ Community Demand -> Requirements Board.
13
+
14
+ Users submit vague product ideas. The app generates a structured specification (problem statement, features, implementation tasks, open questions), and the community can upvote, comment, and claim tasks with links to repos/PRs.
15
+
16
+ ## Stack
17
+
18
+ - Next.js (App Router) + TypeScript
19
+ - Tailwind CSS
20
+ - Prisma + SQLite
21
+ - OpenAI API (optional; app has fallback generation if key is missing)
22
+
23
+ ## Core Features
24
+
25
+ - Cookie-based anonymous identity (`anon_id` UUID, no login)
26
+ - Idea submission + LLM spec generation
27
+ - Home feed with Hot/New sorting
28
+ - Upvotes and comments
29
+ - Task claim/unclaim, status updates, and implementation links
30
+ - Nickname by anonymous identity
31
+ - Basic rate limiting for idea submission (per anon ID + IP)
32
+
33
+ ## Run Locally
34
+
35
+ ```bash
36
+ npm install
37
+ npm run prisma:generate
38
+ npx prisma db push
39
+ npm run dev
40
+ ```
41
+
42
+ Open [http://localhost:3000](http://localhost:3000).
43
+
44
+ ## Environment Variables
45
+
46
+ Copy `.env.example` to `.env`.
47
+
48
+ - `DATABASE_URL` (default: `file:./dev.db`)
49
+ - `OPENAI_API_KEY` (optional)
50
+ - `OPENAI_MODEL` (optional, default `gpt-4.1-mini`)
51
+
52
+ ## Deploy to Hugging Face Spaces (Docker)
53
+
54
+ This repo includes a `Dockerfile` for Spaces. After creating a Docker Space, set optional secrets:
55
+
56
+ - `OPENAI_API_KEY`
57
+ - `OPENAI_MODEL` (optional)
58
+
59
+ The container initializes the SQLite schema at startup using `prisma db push`.
app/api/ideas/[id]/comments/route.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { prisma } from "@/lib/prisma";
4
+ import { getAnonId } from "@/lib/identity";
5
+
6
+ const commentSchema = z.object({
7
+ body: z.string().min(1).max(2000),
8
+ });
9
+
10
+ export async function GET(_: NextRequest, { params }: { params: Promise<{ id: string }> }) {
11
+ const { id } = await params;
12
+ const comments = await prisma.comment.findMany({ where: { ideaId: id }, orderBy: { createdAt: "desc" } });
13
+ return NextResponse.json({ items: comments });
14
+ }
15
+
16
+ export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
17
+ const anonId = await getAnonId();
18
+ const { id } = await params;
19
+
20
+ if (!anonId) {
21
+ return NextResponse.json({ error: "Missing anon identity" }, { status: 400 });
22
+ }
23
+
24
+ const json = await request.json();
25
+ const parsed = commentSchema.safeParse(json);
26
+
27
+ if (!parsed.success) {
28
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
29
+ }
30
+
31
+ const comment = await prisma.comment.create({
32
+ data: {
33
+ ideaId: id,
34
+ body: parsed.data.body,
35
+ createdByAnonId: anonId,
36
+ },
37
+ });
38
+
39
+ await prisma.idea.update({ where: { id }, data: { commentsCount: { increment: 1 } } });
40
+ return NextResponse.json({ comment }, { status: 201 });
41
+ }
app/api/ideas/[id]/route.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { prisma } from "@/lib/prisma";
3
+ import { mapIdea, mapTask } from "@/lib/db-mappers";
4
+ import { getAnonId } from "@/lib/identity";
5
+
6
+ export async function GET(_: NextRequest, { params }: { params: Promise<{ id: string }> }) {
7
+ const anonId = await getAnonId();
8
+ const { id } = await params;
9
+
10
+ const idea = await prisma.idea.findUnique({
11
+ where: { id },
12
+ include: {
13
+ tasks: { include: { links: true }, orderBy: { createdAt: "asc" } },
14
+ comments: { orderBy: { createdAt: "desc" } },
15
+ },
16
+ });
17
+
18
+ if (!idea) {
19
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
20
+ }
21
+
22
+ const claimedAnonIds = Array.from(
23
+ new Set(idea.tasks.map((task) => task.claimedByAnonId).filter((value): value is string => Boolean(value)))
24
+ );
25
+ const claimantNicknames = claimedAnonIds.length
26
+ ? await prisma.nickname.findMany({ where: { anonId: { in: claimedAnonIds } } })
27
+ : [];
28
+ const nicknameByAnonId = new Map(claimantNicknames.map((row) => [row.anonId, row.nickname]));
29
+
30
+ return NextResponse.json({
31
+ idea: {
32
+ ...mapIdea(idea),
33
+ viewerAnonId: anonId,
34
+ tasks: idea.tasks.map((task) => {
35
+ const mapped = mapTask(task);
36
+ return {
37
+ ...mapped,
38
+ claimantNickname: mapped.claimedByAnonId ? nicknameByAnonId.get(mapped.claimedByAnonId) ?? "anon" : null,
39
+ };
40
+ }),
41
+ comments: idea.comments,
42
+ },
43
+ });
44
+ }
app/api/ideas/[id]/upvote/route.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { prisma } from "@/lib/prisma";
3
+ import { getAnonId } from "@/lib/identity";
4
+
5
+ export async function POST(_: NextRequest, { params }: { params: Promise<{ id: string }> }) {
6
+ const anonId = await getAnonId();
7
+ const { id } = await params;
8
+
9
+ if (!anonId) return NextResponse.json({ error: "Missing anon identity" }, { status: 400 });
10
+
11
+ try {
12
+ await prisma.vote.create({
13
+ data: { ideaId: id, anonId },
14
+ });
15
+ } catch {
16
+ return NextResponse.json({ ok: true });
17
+ }
18
+
19
+ await prisma.idea.update({ where: { id }, data: { upvotesCount: { increment: 1 } } });
20
+ return NextResponse.json({ ok: true });
21
+ }
22
+
23
+ export async function DELETE(_: NextRequest, { params }: { params: Promise<{ id: string }> }) {
24
+ const anonId = await getAnonId();
25
+ const { id } = await params;
26
+
27
+ if (!anonId) return NextResponse.json({ error: "Missing anon identity" }, { status: 400 });
28
+
29
+ const existing = await prisma.vote.findUnique({ where: { ideaId_anonId: { ideaId: id, anonId } } });
30
+ if (!existing) return NextResponse.json({ ok: true });
31
+
32
+ await prisma.vote.delete({ where: { ideaId_anonId: { ideaId: id, anonId } } });
33
+ await prisma.idea.update({ where: { id }, data: { upvotesCount: { decrement: 1 } } });
34
+
35
+ return NextResponse.json({ ok: true });
36
+ }
app/api/ideas/route.ts ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { prisma } from "@/lib/prisma";
4
+ import { generateSpec } from "@/lib/llm";
5
+ import { getAnonId, getClientIp } from "@/lib/identity";
6
+ import { mapIdea, mapTask } from "@/lib/db-mappers";
7
+ import { scoreHot } from "@/lib/hot-score";
8
+
9
+ const createIdeaSchema = z.object({
10
+ raw_input_text: z.string().min(20).max(3000),
11
+ target_users: z.string().max(300).optional(),
12
+ platform: z.enum(["Web", "Mobile", "Desktop", "Any"]).optional(),
13
+ constraints: z.string().max(500).optional(),
14
+ });
15
+
16
+ const RATE_LIMIT_PER_HOUR = 5;
17
+
18
+ async function checkRateLimit(anonId: string, ipAddress: string): Promise<boolean> {
19
+ const now = new Date();
20
+ const windowStart = `${now.getUTCFullYear()}-${now.getUTCMonth() + 1}-${now.getUTCDate()}-${now.getUTCHours()}`;
21
+
22
+ const existing = await prisma.submissionRateLimit.findUnique({
23
+ where: {
24
+ anonId_ipAddress_windowStart: { anonId, ipAddress, windowStart },
25
+ },
26
+ });
27
+
28
+ if (!existing) {
29
+ await prisma.submissionRateLimit.create({
30
+ data: { anonId, ipAddress, windowStart, count: 1 },
31
+ });
32
+ return true;
33
+ }
34
+
35
+ if (existing.count >= RATE_LIMIT_PER_HOUR) {
36
+ return false;
37
+ }
38
+
39
+ await prisma.submissionRateLimit.update({
40
+ where: { id: existing.id },
41
+ data: { count: { increment: 1 } },
42
+ });
43
+
44
+ return true;
45
+ }
46
+
47
+ export async function GET(request: NextRequest) {
48
+ const sortParam = request.nextUrl.searchParams.get("sort");
49
+ const sort = sortParam === "new" ? "new" : "hot";
50
+ const rawLimit = Number(request.nextUrl.searchParams.get("limit") || 20);
51
+ const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 50) : 20;
52
+ const cursor = request.nextUrl.searchParams.get("cursor");
53
+ const cursorDate = cursor ? new Date(cursor) : null;
54
+
55
+ const ideas = await prisma.idea.findMany({
56
+ take: limit + 1,
57
+ where: cursorDate && !Number.isNaN(cursorDate.getTime()) ? { createdAt: { lt: cursorDate } } : undefined,
58
+ orderBy: { createdAt: "desc" },
59
+ });
60
+
61
+ const hasMore = ideas.length > limit;
62
+ const page = hasMore ? ideas.slice(0, limit) : ideas;
63
+
64
+ const mapped = page.map((idea) => ({
65
+ ...mapIdea(idea),
66
+ comment_count: idea.commentsCount,
67
+ }));
68
+
69
+ const items =
70
+ sort === "new"
71
+ ? mapped
72
+ : [...mapped].sort((a, b) => scoreHot(b.upvotesCount, b.createdAt) - scoreHot(a.upvotesCount, a.createdAt));
73
+
74
+ const nextCursor = hasMore ? page[page.length - 1]?.createdAt.toISOString() ?? null : null;
75
+ return NextResponse.json({ items, nextCursor });
76
+ }
77
+
78
+ export async function POST(request: NextRequest) {
79
+ const anonId = await getAnonId();
80
+ const ipAddress = await getClientIp();
81
+
82
+ if (!anonId) {
83
+ return NextResponse.json({ error: "Missing anon identity cookie" }, { status: 400 });
84
+ }
85
+
86
+ const allowed = await checkRateLimit(anonId, ipAddress);
87
+ if (!allowed) {
88
+ return NextResponse.json({ error: "Rate limit exceeded. Try again later." }, { status: 429 });
89
+ }
90
+
91
+ const json = await request.json();
92
+ const parsed = createIdeaSchema.safeParse(json);
93
+
94
+ if (!parsed.success) {
95
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
96
+ }
97
+
98
+ try {
99
+ const spec = await generateSpec(parsed.data);
100
+
101
+ const idea = await prisma.idea.create({
102
+ data: {
103
+ createdByAnonId: anonId,
104
+ rawInputText: parsed.data.raw_input_text,
105
+ targetUsers: parsed.data.target_users,
106
+ platform: parsed.data.platform,
107
+ constraints: parsed.data.constraints,
108
+ title: spec.title,
109
+ problemStatement: spec.problem_statement,
110
+ tags: JSON.stringify(spec.tags),
111
+ features: JSON.stringify(spec.features),
112
+ openQuestions: JSON.stringify(spec.open_questions),
113
+ tasks: {
114
+ create: spec.tasks.map((task) => ({
115
+ title: task.title,
116
+ description: task.description,
117
+ acceptance: JSON.stringify(task.acceptance_criteria),
118
+ effort: task.effort,
119
+ status: "OPEN",
120
+ })),
121
+ },
122
+ },
123
+ include: { tasks: { include: { links: true } } },
124
+ });
125
+
126
+ return NextResponse.json(
127
+ {
128
+ idea: {
129
+ ...mapIdea(idea),
130
+ tasks: idea.tasks.map((task) => ({
131
+ ...mapTask(task),
132
+ claimantNickname: null,
133
+ })),
134
+ },
135
+ },
136
+ { status: 201 }
137
+ );
138
+ } catch (error) {
139
+ return NextResponse.json({ error: "Failed to generate idea spec", detail: String(error) }, { status: 500 });
140
+ }
141
+ }
app/api/me/nickname/route.ts ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { prisma } from "@/lib/prisma";
4
+ import { getAnonId } from "@/lib/identity";
5
+
6
+ const schema = z.object({
7
+ nickname: z.string().min(2).max(24),
8
+ });
9
+
10
+ export async function POST(request: NextRequest) {
11
+ const anonId = await getAnonId();
12
+ if (!anonId) return NextResponse.json({ error: "Missing anon identity" }, { status: 400 });
13
+
14
+ const body = await request.json();
15
+ const parsed = schema.safeParse(body);
16
+
17
+ if (!parsed.success) {
18
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
19
+ }
20
+
21
+ const nickname = parsed.data.nickname.trim();
22
+
23
+ await prisma.nickname.upsert({
24
+ where: { anonId },
25
+ create: { anonId, nickname },
26
+ update: { nickname },
27
+ });
28
+
29
+ const res = NextResponse.json({ ok: true, nickname });
30
+ res.cookies.set("nickname", nickname, {
31
+ sameSite: "lax",
32
+ secure: process.env.NODE_ENV === "production",
33
+ path: "/",
34
+ maxAge: 60 * 60 * 24 * 365,
35
+ });
36
+
37
+ return res;
38
+ }
app/api/task-links/[linkId]/route.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { prisma } from "@/lib/prisma";
3
+ import { getAnonId } from "@/lib/identity";
4
+
5
+ export async function DELETE(_: NextRequest, { params }: { params: Promise<{ linkId: string }> }) {
6
+ const anonId = await getAnonId();
7
+ const { linkId } = await params;
8
+
9
+ if (!anonId) return NextResponse.json({ error: "Missing anon identity" }, { status: 400 });
10
+
11
+ const link = await prisma.taskLink.findUnique({ where: { id: linkId }, include: { task: true } });
12
+ if (!link) return NextResponse.json({ error: "Not found" }, { status: 404 });
13
+
14
+ if (link.createdByAnonId !== anonId && link.task.claimedByAnonId !== anonId) {
15
+ return NextResponse.json({ error: "Not allowed" }, { status: 403 });
16
+ }
17
+
18
+ await prisma.taskLink.delete({ where: { id: linkId } });
19
+ return NextResponse.json({ ok: true });
20
+ }
app/api/tasks/[taskId]/claim/route.ts ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { prisma } from "@/lib/prisma";
3
+ import { getAnonId } from "@/lib/identity";
4
+ import { mapTask } from "@/lib/db-mappers";
5
+
6
+ export async function POST(_: NextRequest, { params }: { params: Promise<{ taskId: string }> }) {
7
+ const anonId = await getAnonId();
8
+ const { taskId } = await params;
9
+
10
+ if (!anonId) return NextResponse.json({ error: "Missing anon identity" }, { status: 400 });
11
+
12
+ const task = await prisma.task.findUnique({ where: { id: taskId } });
13
+ if (!task) return NextResponse.json({ error: "Task not found" }, { status: 404 });
14
+ if (task.claimedByAnonId && task.claimedByAnonId !== anonId) {
15
+ return NextResponse.json({ error: "Task already claimed" }, { status: 409 });
16
+ }
17
+
18
+ const updated = await prisma.task.update({
19
+ where: { id: taskId },
20
+ data: {
21
+ claimedByAnonId: anonId,
22
+ claimedAt: new Date(),
23
+ status: task.status === "OPEN" ? "IN_PROGRESS" : task.status,
24
+ },
25
+ include: { links: true },
26
+ });
27
+
28
+ const mapped = mapTask(updated);
29
+ const claimant = await prisma.nickname.findUnique({ where: { anonId } });
30
+
31
+ return NextResponse.json({
32
+ task: {
33
+ ...mapped,
34
+ claimantNickname: claimant?.nickname ?? "anon",
35
+ },
36
+ });
37
+ }
app/api/tasks/[taskId]/links/route.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { prisma } from "@/lib/prisma";
4
+ import { getAnonId } from "@/lib/identity";
5
+
6
+ const schema = z.object({
7
+ url: z.string().url(),
8
+ label: z.string().max(100).optional(),
9
+ });
10
+
11
+ export async function POST(request: NextRequest, { params }: { params: Promise<{ taskId: string }> }) {
12
+ const anonId = await getAnonId();
13
+ const { taskId } = await params;
14
+
15
+ if (!anonId) return NextResponse.json({ error: "Missing anon identity" }, { status: 400 });
16
+
17
+ const json = await request.json();
18
+ const parsed = schema.safeParse(json);
19
+
20
+ if (!parsed.success) {
21
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
22
+ }
23
+
24
+ const task = await prisma.task.findUnique({ where: { id: taskId } });
25
+ if (!task) return NextResponse.json({ error: "Task not found" }, { status: 404 });
26
+
27
+ if (task.claimedByAnonId !== anonId) {
28
+ return NextResponse.json({ error: "Only claimant can add links" }, { status: 403 });
29
+ }
30
+
31
+ const link = await prisma.taskLink.create({
32
+ data: {
33
+ taskId,
34
+ url: parsed.data.url,
35
+ label: parsed.data.label,
36
+ createdByAnonId: anonId,
37
+ },
38
+ });
39
+
40
+ return NextResponse.json({ link }, { status: 201 });
41
+ }
app/api/tasks/[taskId]/status/route.ts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { prisma } from "@/lib/prisma";
4
+ import { getAnonId } from "@/lib/identity";
5
+ import { mapTask } from "@/lib/db-mappers";
6
+
7
+ const schema = z.object({
8
+ status: z.enum(["OPEN", "IN_PROGRESS", "DONE"]),
9
+ });
10
+
11
+ export async function POST(request: NextRequest, { params }: { params: Promise<{ taskId: string }> }) {
12
+ const anonId = await getAnonId();
13
+ const { taskId } = await params;
14
+
15
+ if (!anonId) return NextResponse.json({ error: "Missing anon identity" }, { status: 400 });
16
+
17
+ const json = await request.json();
18
+ const parsed = schema.safeParse(json);
19
+ if (!parsed.success) {
20
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
21
+ }
22
+
23
+ const task = await prisma.task.findUnique({ where: { id: taskId } });
24
+ if (!task) return NextResponse.json({ error: "Task not found" }, { status: 404 });
25
+
26
+ if (task.claimedByAnonId && task.claimedByAnonId !== anonId) {
27
+ return NextResponse.json({ error: "Only claimant can change status" }, { status: 403 });
28
+ }
29
+
30
+ const nextClaimedBy = task.claimedByAnonId ?? anonId;
31
+ const updated = await prisma.task.update({
32
+ where: { id: taskId },
33
+ data: {
34
+ status: parsed.data.status,
35
+ claimedByAnonId: nextClaimedBy,
36
+ claimedAt: task.claimedAt ?? new Date(),
37
+ },
38
+ include: { links: true },
39
+ });
40
+
41
+ const claimant = await prisma.nickname.findUnique({ where: { anonId: nextClaimedBy } });
42
+
43
+ return NextResponse.json({
44
+ task: {
45
+ ...mapTask(updated),
46
+ claimantNickname: claimant?.nickname ?? "anon",
47
+ },
48
+ });
49
+ }
app/api/tasks/[taskId]/unclaim/route.ts ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { prisma } from "@/lib/prisma";
3
+ import { getAnonId } from "@/lib/identity";
4
+ import { mapTask } from "@/lib/db-mappers";
5
+
6
+ export async function POST(_: NextRequest, { params }: { params: Promise<{ taskId: string }> }) {
7
+ const anonId = await getAnonId();
8
+ const { taskId } = await params;
9
+
10
+ if (!anonId) return NextResponse.json({ error: "Missing anon identity" }, { status: 400 });
11
+
12
+ const task = await prisma.task.findUnique({ where: { id: taskId } });
13
+ if (!task) return NextResponse.json({ error: "Task not found" }, { status: 404 });
14
+ if (task.claimedByAnonId !== anonId) {
15
+ return NextResponse.json({ error: "Only claimant can unclaim" }, { status: 403 });
16
+ }
17
+
18
+ const updated = await prisma.task.update({
19
+ where: { id: taskId },
20
+ data: {
21
+ claimedByAnonId: null,
22
+ claimedAt: null,
23
+ status: "OPEN",
24
+ },
25
+ include: { links: true },
26
+ });
27
+
28
+ return NextResponse.json({
29
+ task: {
30
+ ...mapTask(updated),
31
+ claimantNickname: null,
32
+ },
33
+ });
34
+ }
app/globals.css ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
4
+
5
+ :root {
6
+ color-scheme: light;
7
+ --ink: #1f2a37;
8
+ --muted: #5b6473;
9
+ --surface: #fffef9;
10
+ --surface-strong: #ffffff;
11
+ --line: #d7dde8;
12
+ --accent: #0f766e;
13
+ --accent-2: #ea580c;
14
+ }
15
+
16
+ * {
17
+ box-sizing: border-box;
18
+ }
19
+
20
+ html,
21
+ body {
22
+ min-height: 100%;
23
+ }
24
+
25
+ body {
26
+ @apply antialiased;
27
+ color: var(--ink);
28
+ background: linear-gradient(160deg, #f5f2e9 0%, #f4efe4 45%, #f1ece1 100%);
29
+ font-family: var(--font-sans), sans-serif;
30
+ line-height: 1.5;
31
+ }
32
+
33
+ .ambient-bg {
34
+ position: fixed;
35
+ inset: 0;
36
+ pointer-events: none;
37
+ z-index: -1;
38
+ background:
39
+ radial-gradient(36rem 30rem at 10% -10%, rgb(14 116 144 / 0.17), transparent 70%),
40
+ radial-gradient(24rem 22rem at 90% 4%, rgb(234 88 12 / 0.14), transparent 70%),
41
+ radial-gradient(28rem 24rem at 50% 100%, rgb(15 118 110 / 0.1), transparent 70%);
42
+ }
43
+
44
+ .container-page {
45
+ @apply mx-auto w-full max-w-6xl px-4 md:px-6;
46
+ }
47
+
48
+ .brand-mark {
49
+ font-family: var(--font-display), serif;
50
+ letter-spacing: -0.02em;
51
+ }
52
+
53
+ .card {
54
+ @apply rounded-2xl border p-5 shadow-sm transition-all md:p-6;
55
+ border-color: color-mix(in oklab, var(--line) 84%, white);
56
+ background: linear-gradient(180deg, rgb(255 255 255 / 0.9), rgb(255 255 255 / 0.74));
57
+ backdrop-filter: blur(6px);
58
+ }
59
+
60
+ .card:hover {
61
+ box-shadow: 0 12px 28px -22px rgb(15 23 42 / 0.4);
62
+ }
63
+
64
+ .hero-panel {
65
+ @apply rounded-3xl border p-6 md:p-9;
66
+ border-color: rgb(255 255 255 / 0.8);
67
+ background:
68
+ linear-gradient(160deg, rgb(255 255 255 / 0.92) 0%, rgb(249 248 244 / 0.84) 58%, rgb(246 241 234 / 0.92) 100%);
69
+ box-shadow:
70
+ inset 0 1px 0 rgb(255 255 255 / 0.7),
71
+ 0 22px 35px -30px rgb(30 41 59 / 0.45);
72
+ }
73
+
74
+ .section-title {
75
+ @apply text-lg font-semibold tracking-tight md:text-xl;
76
+ font-family: var(--font-display), serif;
77
+ }
78
+
79
+ .kicker {
80
+ @apply text-xs font-semibold uppercase tracking-[0.24em];
81
+ color: var(--muted);
82
+ }
83
+
84
+ .subtle {
85
+ color: var(--muted);
86
+ }
87
+
88
+ .btn {
89
+ @apply inline-flex items-center justify-center rounded-xl border px-3.5 py-2 text-sm font-medium transition duration-200;
90
+ border-color: color-mix(in oklab, var(--line) 86%, white);
91
+ background: rgb(255 255 255 / 0.86);
92
+ color: var(--ink);
93
+ }
94
+
95
+ .btn:hover {
96
+ transform: translateY(-1px);
97
+ box-shadow: 0 10px 22px -18px rgb(15 23 42 / 0.45);
98
+ }
99
+
100
+ .btn:disabled {
101
+ opacity: 0.6;
102
+ transform: none;
103
+ box-shadow: none;
104
+ }
105
+
106
+ .btn-primary {
107
+ border-color: color-mix(in oklab, var(--accent) 64%, var(--accent-2));
108
+ background: linear-gradient(135deg, var(--accent) 0%, color-mix(in oklab, var(--accent) 65%, var(--accent-2)) 100%);
109
+ color: white;
110
+ }
111
+
112
+ .btn-primary:hover {
113
+ filter: saturate(1.05) brightness(0.98);
114
+ }
115
+
116
+ .input {
117
+ @apply w-full rounded-xl border px-3 py-2.5 text-sm outline-none transition;
118
+ border-color: color-mix(in oklab, var(--line) 84%, white);
119
+ background: rgb(255 255 255 / 0.88);
120
+ }
121
+
122
+ .input:focus {
123
+ border-color: color-mix(in oklab, var(--accent) 70%, white);
124
+ box-shadow: 0 0 0 4px rgb(15 118 110 / 0.12);
125
+ }
126
+
127
+ textarea.input {
128
+ resize: vertical;
129
+ }
130
+
131
+ .badge {
132
+ @apply inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium;
133
+ border-color: rgb(14 116 144 / 0.18);
134
+ background: rgb(14 116 144 / 0.08);
135
+ color: rgb(14 116 144 / 0.95);
136
+ }
137
+
138
+ .pill {
139
+ @apply inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium;
140
+ border-color: color-mix(in oklab, var(--line) 80%, white);
141
+ background: rgb(255 255 255 / 0.8);
142
+ color: var(--muted);
143
+ }
144
+
145
+ .metric {
146
+ @apply rounded-xl border px-3 py-2 text-sm;
147
+ border-color: rgb(255 255 255 / 0.75);
148
+ background: rgb(255 255 255 / 0.55);
149
+ }
150
+
151
+ .reveal-up {
152
+ animation: revealUp 420ms ease-out both;
153
+ }
154
+
155
+ @keyframes revealUp {
156
+ from {
157
+ opacity: 0;
158
+ transform: translateY(12px);
159
+ }
160
+
161
+ to {
162
+ opacity: 1;
163
+ transform: translateY(0);
164
+ }
165
+ }
166
+
167
+ @media (prefers-reduced-motion: reduce) {
168
+ .btn,
169
+ .card,
170
+ .reveal-up {
171
+ transition: none;
172
+ animation: none;
173
+ }
174
+ }
app/ideas/[id]/page.tsx ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { notFound } from "next/navigation";
2
+ import { prisma } from "@/lib/prisma";
3
+ import { mapIdea, mapTask } from "@/lib/db-mappers";
4
+ import { getAnonId, getNickname } from "@/lib/identity";
5
+ import { IdeaDetailClient } from "@/components/IdeaDetailClient";
6
+
7
+ const ALLOWED_STATUS = new Set(["OPEN", "IN_PROGRESS", "DONE"] as const);
8
+
9
+ export default async function IdeaPage({ params }: { params: Promise<{ id: string }> }) {
10
+ const { id } = await params;
11
+ const anonId = await getAnonId();
12
+ const nickname = await getNickname();
13
+
14
+ const idea = await prisma.idea.findUnique({
15
+ where: { id },
16
+ include: {
17
+ tasks: { include: { links: true }, orderBy: { createdAt: "asc" } },
18
+ comments: { orderBy: { createdAt: "desc" } },
19
+ },
20
+ });
21
+
22
+ if (!idea) {
23
+ notFound();
24
+ }
25
+
26
+ const vote = anonId
27
+ ? await prisma.vote.findUnique({ where: { ideaId_anonId: { ideaId: id, anonId } } })
28
+ : null;
29
+
30
+ const claimedAnonIds = Array.from(
31
+ new Set(idea.tasks.map((task) => task.claimedByAnonId).filter((value): value is string => Boolean(value)))
32
+ );
33
+ const claimantNicknames = claimedAnonIds.length
34
+ ? await prisma.nickname.findMany({
35
+ where: { anonId: { in: claimedAnonIds } },
36
+ })
37
+ : [];
38
+ const nicknameByAnonId = new Map(claimantNicknames.map((row) => [row.anonId, row.nickname]));
39
+
40
+ const payload = {
41
+ ...mapIdea(idea),
42
+ viewerAnonId: anonId,
43
+ tasks: idea.tasks.map((t) => {
44
+ const mapped = mapTask(t);
45
+ return {
46
+ ...mapped,
47
+ claimantNickname: mapped.claimedByAnonId ? nicknameByAnonId.get(mapped.claimedByAnonId) ?? "anon" : null,
48
+ status: ALLOWED_STATUS.has(mapped.status as "OPEN" | "IN_PROGRESS" | "DONE")
49
+ ? (mapped.status as "OPEN" | "IN_PROGRESS" | "DONE")
50
+ : "OPEN",
51
+ };
52
+ }),
53
+ comments: idea.comments.map((c) => ({ ...c, createdAt: c.createdAt.toISOString() })),
54
+ };
55
+
56
+ return <IdeaDetailClient initialIdea={payload} isVoted={Boolean(vote)} initialNickname={nickname} />;
57
+ }
app/layout.tsx ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Metadata } from "next";
2
+ import Link from "next/link";
3
+ import { Fraunces, Space_Grotesk } from "next/font/google";
4
+ import "./globals.css";
5
+
6
+ export const metadata: Metadata = {
7
+ title: "Demand Solution Board",
8
+ description: "Community demand to implementation board",
9
+ };
10
+
11
+ const sans = Space_Grotesk({
12
+ subsets: ["latin"],
13
+ variable: "--font-sans",
14
+ });
15
+
16
+ const display = Fraunces({
17
+ subsets: ["latin"],
18
+ variable: "--font-display",
19
+ });
20
+
21
+ export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
22
+ return (
23
+ <html lang="en">
24
+ <body className={`${sans.variable} ${display.variable}`}>
25
+ <div className="ambient-bg" />
26
+ <header className="sticky top-0 z-20 border-b border-white/60 bg-white/70 backdrop-blur-xl">
27
+ <div className="container-page flex items-center justify-between py-5">
28
+ <Link href="/" className="brand-mark text-lg font-semibold tracking-tight">
29
+ Demand Solution Board
30
+ </Link>
31
+ <div className="flex items-center gap-2">
32
+ <Link href="/" className="btn">
33
+ Browse
34
+ </Link>
35
+ <Link href="/submit" className="btn btn-primary">
36
+ Submit Idea
37
+ </Link>
38
+ </div>
39
+ </div>
40
+ </header>
41
+ <main className="container-page pb-12">{children}</main>
42
+ </body>
43
+ </html>
44
+ );
45
+ }
app/page.tsx ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Link from "next/link";
2
+ import { HomeList } from "@/components/HomeList";
3
+
4
+ export default function HomePage() {
5
+ return (
6
+ <div className="space-y-6 md:space-y-8">
7
+ <section className="hero-panel reveal-up">
8
+ <p className="kicker">Community Product Lab</p>
9
+ <div className="mt-3 grid gap-5 md:grid-cols-[1.7fr_1fr] md:items-end">
10
+ <div>
11
+ <h1 className="section-title text-3xl md:text-5xl">Turn rough ideas into a build-ready requirements board.</h1>
12
+ <p className="subtle mt-4 max-w-2xl text-sm md:text-base">
13
+ Post a fuzzy concept, generate a structured spec with tasks, let the community validate demand, and let developers
14
+ claim work with repo and PR links.
15
+ </p>
16
+ <div className="mt-5 flex flex-wrap gap-2">
17
+ <Link href="/submit" className="btn btn-primary">
18
+ Start a New Idea
19
+ </Link>
20
+ <span className="pill">No login required</span>
21
+ <span className="pill">Cookie-based identity</span>
22
+ </div>
23
+ </div>
24
+
25
+ <div className="grid gap-2">
26
+ <div className="metric">
27
+ <p className="text-xs uppercase tracking-[0.2em] text-zinc-500">Input</p>
28
+ <p className="mt-1 text-sm font-medium">Vague idea + constraints</p>
29
+ </div>
30
+ <div className="metric">
31
+ <p className="text-xs uppercase tracking-[0.2em] text-zinc-500">Output</p>
32
+ <p className="mt-1 text-sm font-medium">Features, tasks, open questions</p>
33
+ </div>
34
+ <div className="metric">
35
+ <p className="text-xs uppercase tracking-[0.2em] text-zinc-500">Execution</p>
36
+ <p className="mt-1 text-sm font-medium">Claim tasks and ship with links</p>
37
+ </div>
38
+ </div>
39
+ </div>
40
+ </section>
41
+
42
+ <section className="reveal-up" style={{ animationDelay: "80ms" }}>
43
+ <div className="mb-3 flex items-center justify-between">
44
+ <h2 className="section-title">Idea Board</h2>
45
+ <p className="subtle text-sm">Sorted by hotness or recency</p>
46
+ </div>
47
+ <HomeList />
48
+ </section>
49
+ </div>
50
+ );
51
+ }
app/submit/page.tsx ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { SubmitForm } from "@/components/SubmitForm";
2
+
3
+ export default function SubmitPage() {
4
+ return (
5
+ <div className="space-y-5 md:space-y-6">
6
+ <section className="hero-panel reveal-up">
7
+ <p className="kicker">Submit Demand</p>
8
+ <h1 className="section-title mt-2 text-3xl md:text-4xl">Generate a public requirements board from your idea.</h1>
9
+ <p className="subtle mt-3 max-w-3xl text-sm md:text-base">
10
+ Describe the product need in plain language. The system will produce a buildable spec with core features, actionable
11
+ tasks, and open questions.
12
+ </p>
13
+ </section>
14
+ <SubmitForm />
15
+ </div>
16
+ );
17
+ }
components/HomeList.tsx ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import Link from "next/link";
4
+ import { useEffect, useMemo, useState } from "react";
5
+
6
+ type IdeaCard = {
7
+ id: string;
8
+ title: string;
9
+ problemStatement: string;
10
+ tags: string[];
11
+ upvotesCount: number;
12
+ comment_count: number;
13
+ createdAt: string;
14
+ };
15
+
16
+ export function HomeList() {
17
+ const [sort, setSort] = useState<"hot" | "new">("hot");
18
+ const [loading, setLoading] = useState(true);
19
+ const [items, setItems] = useState<IdeaCard[]>([]);
20
+ const [error, setError] = useState("");
21
+
22
+ useEffect(() => {
23
+ let active = true;
24
+ setLoading(true);
25
+ setError("");
26
+
27
+ fetch(`/api/ideas?sort=${sort}`)
28
+ .then(async (response) => {
29
+ const data = await response.json();
30
+ if (!response.ok) {
31
+ throw new Error(data.error || "Failed to load ideas");
32
+ }
33
+ return data;
34
+ })
35
+ .then((data) => {
36
+ if (active) setItems(data.items || []);
37
+ })
38
+ .catch((err) => {
39
+ if (active) {
40
+ setItems([]);
41
+ setError(err instanceof Error ? err.message : "Failed to load ideas");
42
+ }
43
+ })
44
+ .finally(() => {
45
+ if (active) setLoading(false);
46
+ });
47
+
48
+ return () => {
49
+ active = false;
50
+ };
51
+ }, [sort]);
52
+
53
+ const empty = useMemo(() => !loading && !error && items.length === 0, [loading, error, items.length]);
54
+
55
+ return (
56
+ <div className="space-y-4">
57
+ <div className="flex flex-wrap items-center justify-between gap-2">
58
+ <div className="flex items-center gap-2 rounded-full border border-white/70 bg-white/60 p-1">
59
+ <button onClick={() => setSort("hot")} className={`btn rounded-full px-4 ${sort === "hot" ? "btn-primary" : ""}`}>
60
+ Hot
61
+ </button>
62
+ <button onClick={() => setSort("new")} className={`btn rounded-full px-4 ${sort === "new" ? "btn-primary" : ""}`}>
63
+ New
64
+ </button>
65
+ </div>
66
+ <p className="subtle text-sm">{items.length} ideas</p>
67
+ </div>
68
+
69
+ {loading ? <p className="subtle text-sm">Loading ideas...</p> : null}
70
+ {error ? <p className="text-sm text-red-700">{error}</p> : null}
71
+ {empty ? <p className="subtle text-sm">No ideas yet. Be the first to submit one.</p> : null}
72
+
73
+ <div className="grid gap-3">
74
+ {items.map((idea, index) => (
75
+ <Link
76
+ key={idea.id}
77
+ href={`/ideas/${idea.id}`}
78
+ className="card block reveal-up"
79
+ style={{ animationDelay: `${Math.min(index * 45, 240)}ms` }}
80
+ >
81
+ <div className="flex flex-wrap items-start justify-between gap-2">
82
+ <h3 className="text-base font-semibold md:text-lg">{idea.title}</h3>
83
+ <span className="subtle text-xs">{new Date(idea.createdAt).toLocaleString()}</span>
84
+ </div>
85
+
86
+ <p className="subtle mt-2 text-sm">{idea.problemStatement}</p>
87
+
88
+ {idea.tags.length ? (
89
+ <div className="mt-4 flex flex-wrap gap-1.5">
90
+ {idea.tags.slice(0, 6).map((tag) => (
91
+ <span key={tag} className="badge">
92
+ {tag}
93
+ </span>
94
+ ))}
95
+ </div>
96
+ ) : null}
97
+
98
+ <div className="mt-4 grid grid-cols-2 gap-2 md:max-w-xs">
99
+ <div className="metric">
100
+ <p className="text-xs uppercase tracking-[0.16em] text-zinc-500">Upvotes</p>
101
+ <p className="mt-1 text-sm font-semibold">{idea.upvotesCount}</p>
102
+ </div>
103
+ <div className="metric">
104
+ <p className="text-xs uppercase tracking-[0.16em] text-zinc-500">Comments</p>
105
+ <p className="mt-1 text-sm font-semibold">{idea.comment_count}</p>
106
+ </div>
107
+ </div>
108
+ </Link>
109
+ ))}
110
+ </div>
111
+ </div>
112
+ );
113
+ }
components/IdeaDetailClient.tsx ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useMemo, useState } from "react";
4
+
5
+ type LinkItem = {
6
+ id: string;
7
+ url: string;
8
+ label: string | null;
9
+ createdByAnonId: string;
10
+ };
11
+
12
+ type TaskItem = {
13
+ id: string;
14
+ title: string;
15
+ description: string | null;
16
+ acceptance_criteria: string[];
17
+ effort: string | null;
18
+ status: "OPEN" | "IN_PROGRESS" | "DONE";
19
+ claimedByAnonId: string | null;
20
+ claimantNickname: string | null;
21
+ links: LinkItem[];
22
+ };
23
+
24
+ type CommentItem = {
25
+ id: string;
26
+ body: string;
27
+ createdAt: string;
28
+ };
29
+
30
+ type IdeaPayload = {
31
+ id: string;
32
+ title: string;
33
+ problemStatement: string;
34
+ tags: string[];
35
+ features: string[];
36
+ open_questions: string[];
37
+ upvotesCount: number;
38
+ commentsCount: number;
39
+ viewerAnonId: string;
40
+ tasks: TaskItem[];
41
+ comments: CommentItem[];
42
+ };
43
+
44
+ type TaskUpdate = {
45
+ id: string;
46
+ status: "OPEN" | "IN_PROGRESS" | "DONE";
47
+ claimedByAnonId: string | null;
48
+ claimantNickname?: string | null;
49
+ links?: LinkItem[];
50
+ };
51
+
52
+ function formatStatus(status: TaskItem["status"]): string {
53
+ if (status === "IN_PROGRESS") return "In Progress";
54
+ if (status === "DONE") return "Done";
55
+ return "Open";
56
+ }
57
+
58
+ export function IdeaDetailClient({
59
+ initialIdea,
60
+ isVoted,
61
+ initialNickname,
62
+ }: {
63
+ initialIdea: IdeaPayload;
64
+ isVoted: boolean;
65
+ initialNickname: string;
66
+ }) {
67
+ const [idea, setIdea] = useState(initialIdea);
68
+ const [voted, setVoted] = useState(isVoted);
69
+ const [nickname, setNickname] = useState(initialNickname);
70
+ const [nickInput, setNickInput] = useState(initialNickname);
71
+ const [commentInput, setCommentInput] = useState("");
72
+
73
+ function applyTaskUpdate(taskId: string, taskUpdate: TaskUpdate) {
74
+ setIdea((prev) => ({
75
+ ...prev,
76
+ tasks: prev.tasks.map((task) => {
77
+ if (task.id !== taskId) return task;
78
+
79
+ const nextClaimedBy = taskUpdate.claimedByAnonId;
80
+ const nextClaimantNickname =
81
+ taskUpdate.claimantNickname !== undefined
82
+ ? taskUpdate.claimantNickname
83
+ : nextClaimedBy === prev.viewerAnonId
84
+ ? nickname || "anon"
85
+ : task.claimantNickname;
86
+
87
+ return {
88
+ ...task,
89
+ status: taskUpdate.status,
90
+ claimedByAnonId: nextClaimedBy,
91
+ claimantNickname: nextClaimedBy ? nextClaimantNickname ?? "anon" : null,
92
+ links: taskUpdate.links ?? task.links,
93
+ };
94
+ }),
95
+ }));
96
+ }
97
+
98
+ async function toggleVote() {
99
+ const next = !voted;
100
+ setVoted(next);
101
+ setIdea((prev) => ({ ...prev, upvotesCount: prev.upvotesCount + (next ? 1 : -1) }));
102
+
103
+ const method = next ? "POST" : "DELETE";
104
+ const response = await fetch(`/api/ideas/${idea.id}/upvote`, { method });
105
+ if (!response.ok) {
106
+ setVoted(!next);
107
+ setIdea((prev) => ({ ...prev, upvotesCount: prev.upvotesCount + (next ? -1 : 1) }));
108
+ }
109
+ }
110
+
111
+ async function saveNickname() {
112
+ const response = await fetch("/api/me/nickname", {
113
+ method: "POST",
114
+ headers: { "Content-Type": "application/json" },
115
+ body: JSON.stringify({ nickname: nickInput }),
116
+ });
117
+
118
+ if (response.ok) {
119
+ setNickname(nickInput);
120
+ setIdea((prev) => ({
121
+ ...prev,
122
+ tasks: prev.tasks.map((task) =>
123
+ task.claimedByAnonId === prev.viewerAnonId ? { ...task, claimantNickname: nickInput || "anon" } : task
124
+ ),
125
+ }));
126
+ }
127
+ }
128
+
129
+ async function addComment() {
130
+ const body = commentInput.trim();
131
+ if (!body) return;
132
+
133
+ const response = await fetch(`/api/ideas/${idea.id}/comments`, {
134
+ method: "POST",
135
+ headers: { "Content-Type": "application/json" },
136
+ body: JSON.stringify({ body }),
137
+ });
138
+
139
+ if (!response.ok) return;
140
+ const data = await response.json();
141
+
142
+ setIdea((prev) => ({
143
+ ...prev,
144
+ commentsCount: prev.commentsCount + 1,
145
+ comments: [data.comment, ...prev.comments],
146
+ }));
147
+ setCommentInput("");
148
+ }
149
+
150
+ async function claim(taskId: string) {
151
+ const response = await fetch(`/api/tasks/${taskId}/claim`, { method: "POST" });
152
+ if (!response.ok) return;
153
+
154
+ const data = await response.json();
155
+ applyTaskUpdate(taskId, data.task);
156
+ }
157
+
158
+ async function unclaim(taskId: string) {
159
+ const response = await fetch(`/api/tasks/${taskId}/unclaim`, { method: "POST" });
160
+ if (!response.ok) return;
161
+
162
+ const data = await response.json();
163
+ applyTaskUpdate(taskId, data.task);
164
+ }
165
+
166
+ async function setStatus(taskId: string, status: TaskItem["status"]) {
167
+ const response = await fetch(`/api/tasks/${taskId}/status`, {
168
+ method: "POST",
169
+ headers: { "Content-Type": "application/json" },
170
+ body: JSON.stringify({ status }),
171
+ });
172
+ if (!response.ok) return;
173
+
174
+ const data = await response.json();
175
+ applyTaskUpdate(taskId, data.task);
176
+ }
177
+
178
+ async function addLink(taskId: string) {
179
+ const url = window.prompt("Paste URL (repo/PR/demo)");
180
+ if (!url) return;
181
+ const label = window.prompt("Label (optional)") || undefined;
182
+
183
+ const response = await fetch(`/api/tasks/${taskId}/links`, {
184
+ method: "POST",
185
+ headers: { "Content-Type": "application/json" },
186
+ body: JSON.stringify({ url, label }),
187
+ });
188
+
189
+ if (!response.ok) return;
190
+ const data = await response.json();
191
+
192
+ setIdea((prev) => ({
193
+ ...prev,
194
+ tasks: prev.tasks.map((task) => (task.id === taskId ? { ...task, links: [...task.links, data.link] } : task)),
195
+ }));
196
+ }
197
+
198
+ async function removeLink(taskId: string, linkId: string) {
199
+ const response = await fetch(`/api/task-links/${linkId}`, { method: "DELETE" });
200
+ if (!response.ok) return;
201
+
202
+ setIdea((prev) => ({
203
+ ...prev,
204
+ tasks: prev.tasks.map((task) =>
205
+ task.id === taskId
206
+ ? {
207
+ ...task,
208
+ links: task.links.filter((link) => link.id !== linkId),
209
+ }
210
+ : task
211
+ ),
212
+ }));
213
+ }
214
+
215
+ const grouped = useMemo(() => {
216
+ return {
217
+ open: idea.tasks.filter((task) => task.status === "OPEN"),
218
+ inProgress: idea.tasks.filter((task) => task.status === "IN_PROGRESS"),
219
+ done: idea.tasks.filter((task) => task.status === "DONE"),
220
+ };
221
+ }, [idea.tasks]);
222
+
223
+ return (
224
+ <div className="space-y-5 md:space-y-6">
225
+ <section className="hero-panel reveal-up">
226
+ <p className="kicker">Generated Idea</p>
227
+ <h1 className="section-title mt-2 text-3xl md:text-4xl">{idea.title}</h1>
228
+ <p className="subtle mt-4 max-w-4xl text-sm md:text-base">{idea.problemStatement}</p>
229
+
230
+ <div className="mt-4 flex flex-wrap gap-1.5">
231
+ {idea.tags.map((tag) => (
232
+ <span key={tag} className="badge">
233
+ {tag}
234
+ </span>
235
+ ))}
236
+ </div>
237
+
238
+ <div className="mt-5 flex flex-wrap items-center gap-2 md:gap-3">
239
+ <button className={`btn ${voted ? "btn-primary" : ""}`} onClick={toggleVote}>
240
+ {voted ? "Upvoted" : "Upvote"} ({idea.upvotesCount})
241
+ </button>
242
+ <span className="pill">{idea.commentsCount} comments</span>
243
+ <span className="pill">{idea.tasks.length} tasks</span>
244
+ </div>
245
+ </section>
246
+
247
+ <section className="grid gap-4 md:grid-cols-2 reveal-up" style={{ animationDelay: "80ms" }}>
248
+ <div className="card">
249
+ <h2 className="section-title text-xl">Core Features</h2>
250
+ <ul className="mt-3 list-disc space-y-2 pl-5 text-sm">
251
+ {idea.features.map((feature) => (
252
+ <li key={feature}>{feature}</li>
253
+ ))}
254
+ </ul>
255
+ </div>
256
+
257
+ <div className="card">
258
+ <h2 className="section-title text-xl">Open Questions</h2>
259
+ <ul className="mt-3 list-disc space-y-2 pl-5 text-sm">
260
+ {idea.open_questions.length ? idea.open_questions.map((question) => <li key={question}>{question}</li>) : <li>None</li>}
261
+ </ul>
262
+ </div>
263
+ </section>
264
+
265
+ <section className="card reveal-up space-y-4" style={{ animationDelay: "140ms" }}>
266
+ <div className="flex flex-wrap items-end justify-between gap-3">
267
+ <div>
268
+ <h2 className="section-title">Developer Identity</h2>
269
+ <p className="subtle mt-1 text-sm">Set a nickname shown when you claim tasks.</p>
270
+ </div>
271
+ <span className="pill">Current: {nickname || "anon"}</span>
272
+ </div>
273
+
274
+ <div className="flex flex-wrap items-end gap-2">
275
+ <div className="w-full max-w-sm">
276
+ <label className="mb-1.5 block text-sm font-medium">Nickname</label>
277
+ <input className="input" value={nickInput} onChange={(event) => setNickInput(event.target.value)} />
278
+ </div>
279
+ <button className="btn" onClick={saveNickname}>
280
+ Save Nickname
281
+ </button>
282
+ </div>
283
+ </section>
284
+
285
+ <section className="card reveal-up space-y-4" style={{ animationDelay: "180ms" }}>
286
+ <div className="flex items-end justify-between gap-2">
287
+ <div>
288
+ <h2 className="section-title">Tasks</h2>
289
+ <p className="subtle mt-1 text-sm">Claim tasks, attach implementation links, and move status to done.</p>
290
+ </div>
291
+ </div>
292
+
293
+ <TaskColumn
294
+ title="Open"
295
+ items={grouped.open}
296
+ viewerAnonId={idea.viewerAnonId}
297
+ onClaim={claim}
298
+ onUnclaim={unclaim}
299
+ onSetStatus={setStatus}
300
+ onAddLink={addLink}
301
+ onRemoveLink={removeLink}
302
+ />
303
+ <TaskColumn
304
+ title="In Progress"
305
+ items={grouped.inProgress}
306
+ viewerAnonId={idea.viewerAnonId}
307
+ onClaim={claim}
308
+ onUnclaim={unclaim}
309
+ onSetStatus={setStatus}
310
+ onAddLink={addLink}
311
+ onRemoveLink={removeLink}
312
+ />
313
+ <TaskColumn
314
+ title="Done"
315
+ items={grouped.done}
316
+ viewerAnonId={idea.viewerAnonId}
317
+ onClaim={claim}
318
+ onUnclaim={unclaim}
319
+ onSetStatus={setStatus}
320
+ onAddLink={addLink}
321
+ onRemoveLink={removeLink}
322
+ />
323
+ </section>
324
+
325
+ <section className="card reveal-up space-y-4" style={{ animationDelay: "240ms" }}>
326
+ <div className="flex items-end justify-between gap-2">
327
+ <h2 className="section-title">Comments</h2>
328
+ <span className="pill">{idea.commentsCount} total</span>
329
+ </div>
330
+
331
+ <div className="flex flex-col gap-2 md:flex-row">
332
+ <input
333
+ className="input"
334
+ value={commentInput}
335
+ onChange={(event) => setCommentInput(event.target.value)}
336
+ placeholder="Add a comment"
337
+ />
338
+ <button className="btn btn-primary md:min-w-28" onClick={addComment}>
339
+ Post
340
+ </button>
341
+ </div>
342
+
343
+ <div className="space-y-2">
344
+ {idea.comments.length ? (
345
+ idea.comments.map((comment) => (
346
+ <div key={comment.id} className="rounded-xl border border-white/70 bg-white/60 p-3 text-sm">
347
+ <p>{comment.body}</p>
348
+ <p className="subtle mt-1 text-xs">{new Date(comment.createdAt).toLocaleString()}</p>
349
+ </div>
350
+ ))
351
+ ) : (
352
+ <p className="subtle text-sm">No comments yet.</p>
353
+ )}
354
+ </div>
355
+ </section>
356
+ </div>
357
+ );
358
+ }
359
+
360
+ function statusBadgeClass(status: TaskItem["status"]): string {
361
+ if (status === "DONE") return "bg-emerald-100 text-emerald-700 border-emerald-200";
362
+ if (status === "IN_PROGRESS") return "bg-amber-100 text-amber-700 border-amber-200";
363
+ return "bg-sky-100 text-sky-700 border-sky-200";
364
+ }
365
+
366
+ function TaskColumn({
367
+ title,
368
+ items,
369
+ viewerAnonId,
370
+ onClaim,
371
+ onUnclaim,
372
+ onSetStatus,
373
+ onAddLink,
374
+ onRemoveLink,
375
+ }: {
376
+ title: string;
377
+ items: TaskItem[];
378
+ viewerAnonId: string;
379
+ onClaim: (taskId: string) => Promise<void>;
380
+ onUnclaim: (taskId: string) => Promise<void>;
381
+ onSetStatus: (taskId: string, status: TaskItem["status"]) => Promise<void>;
382
+ onAddLink: (taskId: string) => Promise<void>;
383
+ onRemoveLink: (taskId: string, linkId: string) => Promise<void>;
384
+ }) {
385
+ return (
386
+ <div className="space-y-2">
387
+ <h3 className="text-sm font-semibold uppercase tracking-[0.16em] text-zinc-600">{title}</h3>
388
+ {items.length === 0 ? <p className="subtle text-sm">No tasks.</p> : null}
389
+ {items.map((task) => {
390
+ const isClaimedByMe = task.claimedByAnonId === viewerAnonId;
391
+ const isClaimedBySomeoneElse = Boolean(task.claimedByAnonId) && !isClaimedByMe;
392
+
393
+ return (
394
+ <details key={task.id} className="rounded-xl border border-white/70 bg-white/70 p-3">
395
+ <summary className="cursor-pointer text-sm font-semibold">
396
+ <span>{task.title}</span>
397
+ <span className={`ml-2 inline-flex rounded-full border px-2 py-0.5 text-xs ${statusBadgeClass(task.status)}`}>
398
+ {formatStatus(task.status)}
399
+ </span>
400
+ {task.effort ? <span className="ml-2 text-xs text-zinc-500">Effort {task.effort}</span> : null}
401
+ </summary>
402
+
403
+ <div className="mt-3 space-y-2 text-sm">
404
+ {task.description ? <p>{task.description}</p> : null}
405
+ {task.claimedByAnonId ? (
406
+ <p className="text-xs text-zinc-600">
407
+ Claimed by <span className="font-medium">{task.claimantNickname || "anon"}</span>
408
+ </p>
409
+ ) : (
410
+ <p className="text-xs text-zinc-600">Unclaimed</p>
411
+ )}
412
+
413
+ {task.acceptance_criteria.length > 0 ? (
414
+ <ul className="list-disc space-y-1 pl-5">
415
+ {task.acceptance_criteria.map((criteria) => (
416
+ <li key={criteria}>{criteria}</li>
417
+ ))}
418
+ </ul>
419
+ ) : null}
420
+
421
+ <div className="flex flex-wrap gap-2">
422
+ {!task.claimedByAnonId ? (
423
+ <button className="btn" onClick={() => onClaim(task.id)}>
424
+ Claim
425
+ </button>
426
+ ) : null}
427
+
428
+ {isClaimedByMe ? (
429
+ <>
430
+ <button className="btn" onClick={() => onUnclaim(task.id)}>
431
+ Unclaim
432
+ </button>
433
+ <button className="btn" onClick={() => onSetStatus(task.id, "IN_PROGRESS")}>
434
+ In Progress
435
+ </button>
436
+ <button className="btn" onClick={() => onSetStatus(task.id, "DONE")}>
437
+ Done
438
+ </button>
439
+ <button className="btn" onClick={() => onSetStatus(task.id, "OPEN")}>
440
+ Open
441
+ </button>
442
+ <button className="btn" onClick={() => onAddLink(task.id)}>
443
+ Add Link
444
+ </button>
445
+ </>
446
+ ) : null}
447
+
448
+ {isClaimedBySomeoneElse ? <span className="subtle text-xs">Only claimant can update this task.</span> : null}
449
+ </div>
450
+
451
+ <div className="space-y-1.5">
452
+ {task.links.map((link) => {
453
+ const canRemove = isClaimedByMe || link.createdByAnonId === viewerAnonId;
454
+ return (
455
+ <div key={link.id} className="flex items-center justify-between gap-2 rounded-lg border border-zinc-200 bg-white/90 px-2 py-1">
456
+ <a href={link.url} target="_blank" rel="noreferrer" className="truncate text-cyan-700 underline">
457
+ {link.label || link.url}
458
+ </a>
459
+ {canRemove ? (
460
+ <button className="text-xs text-zinc-500" onClick={() => onRemoveLink(task.id, link.id)}>
461
+ remove
462
+ </button>
463
+ ) : null}
464
+ </div>
465
+ );
466
+ })}
467
+ </div>
468
+ </div>
469
+ </details>
470
+ );
471
+ })}
472
+ </div>
473
+ );
474
+ }
components/SubmitForm.tsx ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useRouter } from "next/navigation";
4
+ import { useMemo, useState } from "react";
5
+
6
+ function parseErrorMessage(error: unknown): string {
7
+ if (typeof error === "string") return error;
8
+ if (!error || typeof error !== "object") return "Failed to generate requirements.";
9
+
10
+ const value = error as Record<string, unknown>;
11
+ if (typeof value.error === "string") return value.error;
12
+ if (typeof value.detail === "string") return value.detail;
13
+
14
+ return "Failed to generate requirements.";
15
+ }
16
+
17
+ export function SubmitForm() {
18
+ const router = useRouter();
19
+ const [rawText, setRawText] = useState("");
20
+ const [targetUsers, setTargetUsers] = useState("");
21
+ const [platform, setPlatform] = useState("Any");
22
+ const [constraints, setConstraints] = useState("");
23
+ const [loading, setLoading] = useState(false);
24
+ const [error, setError] = useState("");
25
+
26
+ const chars = useMemo(() => rawText.length, [rawText.length]);
27
+
28
+ async function onSubmit(e: React.FormEvent) {
29
+ e.preventDefault();
30
+ setError("");
31
+ setLoading(true);
32
+
33
+ try {
34
+ const response = await fetch("/api/ideas", {
35
+ method: "POST",
36
+ headers: { "Content-Type": "application/json" },
37
+ body: JSON.stringify({
38
+ raw_input_text: rawText,
39
+ target_users: targetUsers || undefined,
40
+ platform: platform === "Any" ? undefined : platform,
41
+ constraints: constraints || undefined,
42
+ }),
43
+ });
44
+
45
+ const data = await response.json();
46
+ if (!response.ok) {
47
+ throw new Error(parseErrorMessage(data));
48
+ }
49
+
50
+ router.push(`/ideas/${data.idea.id}`);
51
+ router.refresh();
52
+ } catch (err) {
53
+ setError(err instanceof Error ? err.message : "Unknown error.");
54
+ } finally {
55
+ setLoading(false);
56
+ }
57
+ }
58
+
59
+ return (
60
+ <form onSubmit={onSubmit} className="card reveal-up space-y-5" style={{ animationDelay: "80ms" }}>
61
+ <div className="grid gap-5 md:grid-cols-2">
62
+ <div className="md:col-span-2">
63
+ <div className="mb-1.5 flex items-center justify-between gap-2">
64
+ <label className="text-sm font-semibold">Idea text</label>
65
+ <span className={`text-xs ${chars < 20 ? "text-red-700" : "subtle"}`}>{chars}/3000</span>
66
+ </div>
67
+ <textarea
68
+ required
69
+ minLength={20}
70
+ maxLength={3000}
71
+ value={rawText}
72
+ onChange={(e) => setRawText(e.target.value)}
73
+ className="input min-h-52"
74
+ placeholder="Example: A neighborhood demand board where residents post local pain points and developers build solutions..."
75
+ />
76
+ <p className="subtle mt-2 text-xs">Be concrete about the problem and expected outcome to get better generated tasks.</p>
77
+ </div>
78
+
79
+ <div>
80
+ <label className="mb-1.5 block text-sm font-semibold">Target users (optional)</label>
81
+ <input
82
+ value={targetUsers}
83
+ onChange={(e) => setTargetUsers(e.target.value)}
84
+ className="input"
85
+ placeholder="Independent creators, student teams, local shops..."
86
+ maxLength={300}
87
+ />
88
+ </div>
89
+
90
+ <div>
91
+ <label className="mb-1.5 block text-sm font-semibold">Platform preference (optional)</label>
92
+ <select value={platform} onChange={(e) => setPlatform(e.target.value)} className="input">
93
+ <option>Any</option>
94
+ <option>Web</option>
95
+ <option>Mobile</option>
96
+ <option>Desktop</option>
97
+ </select>
98
+ </div>
99
+
100
+ <div className="md:col-span-2">
101
+ <label className="mb-1.5 block text-sm font-semibold">Constraints (optional)</label>
102
+ <input
103
+ value={constraints}
104
+ onChange={(e) => setConstraints(e.target.value)}
105
+ className="input"
106
+ placeholder="No login, privacy-first, low budget, integrate with GitHub only..."
107
+ maxLength={500}
108
+ />
109
+ </div>
110
+ </div>
111
+
112
+ <div className="rounded-xl border border-amber-200 bg-amber-50/80 p-3 text-xs text-amber-900">
113
+ Disclaimer: this is a best-effort generated specification. Review tasks and open questions before building.
114
+ </div>
115
+
116
+ <div className="flex flex-wrap items-center gap-3">
117
+ <button disabled={loading} className="btn btn-primary min-w-52">
118
+ {loading ? (
119
+ <span className="inline-flex items-center gap-2">
120
+ <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-white/80 border-t-transparent" />
121
+ Generating requirements...
122
+ </span>
123
+ ) : (
124
+ "Generate Requirements"
125
+ )}
126
+ </button>
127
+ <p className="subtle text-xs">Rate-limited to 5 submissions/hour per anonymous identity and IP.</p>
128
+ </div>
129
+
130
+ {error ? <p className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">{error}</p> : null}
131
+ </form>
132
+ );
133
+ }
lib/db-mappers.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Idea, Task, TaskLink } from "@prisma/client";
2
+
3
+ export function parseJsonArray<T>(value: string, fallback: T[] = []): T[] {
4
+ try {
5
+ return JSON.parse(value) as T[];
6
+ } catch {
7
+ return fallback;
8
+ }
9
+ }
10
+
11
+ export function mapIdea(idea: Idea) {
12
+ return {
13
+ ...idea,
14
+ tags: parseJsonArray<string>(idea.tags),
15
+ features: parseJsonArray<string>(idea.features),
16
+ open_questions: parseJsonArray<string>(idea.openQuestions),
17
+ };
18
+ }
19
+
20
+ export function mapTask(task: Task & { links?: TaskLink[] }) {
21
+ return {
22
+ ...task,
23
+ acceptance_criteria: parseJsonArray<string>(task.acceptance),
24
+ links: task.links ?? [],
25
+ };
26
+ }
lib/hot-score.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export function scoreHot(upvotes: number, createdAt: Date): number {
2
+ const ageHours = Math.max(1, (Date.now() - createdAt.getTime()) / 3600000);
3
+ return upvotes / Math.pow(ageHours + 2, 0.8);
4
+ }
lib/identity.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { cookies, headers } from "next/headers";
2
+
3
+ export async function getAnonId(): Promise<string> {
4
+ const store = await cookies();
5
+ return store.get("anon_id")?.value ?? "";
6
+ }
7
+
8
+ export async function getNickname(): Promise<string> {
9
+ const store = await cookies();
10
+ return store.get("nickname")?.value ?? "anon";
11
+ }
12
+
13
+ export async function getClientIp(): Promise<string> {
14
+ const h = await headers();
15
+ const forwarded = h.get("x-forwarded-for");
16
+ if (forwarded) {
17
+ return forwarded.split(",")[0]?.trim() || "unknown";
18
+ }
19
+ return h.get("x-real-ip") ?? "unknown";
20
+ }
lib/llm.ts ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OpenAI from "openai";
2
+ import { generatedSpecSchema, type GeneratedSpec } from "@/lib/spec-schema";
3
+
4
+ const openai = process.env.OPENAI_API_KEY
5
+ ? new OpenAI({ apiKey: process.env.OPENAI_API_KEY })
6
+ : null;
7
+
8
+ function fallbackSpec(rawInputText: string, platform?: string | null, targetUsers?: string | null): GeneratedSpec {
9
+ const title = rawInputText.slice(0, 80) || "Community Idea";
10
+ const audience = targetUsers?.trim() || "general users";
11
+ const targetPlatform = platform?.trim() || "web";
12
+
13
+ return {
14
+ title,
15
+ problem_statement: `Build a ${targetPlatform} product for ${audience} based on the submitted idea.`,
16
+ tags: ["community", "spec"],
17
+ features: [
18
+ "Idea submission form with optional context fields",
19
+ "LLM-based requirement generation",
20
+ "Public idea detail page with structured sections",
21
+ ],
22
+ tasks: [
23
+ { title: "Set up project scaffold", description: "Initialize Next.js + Prisma + SQLite", acceptance_criteria: ["Project runs locally"], effort: "S" },
24
+ { title: "Add anon identity middleware", description: "Create persistent anon_id cookie", acceptance_criteria: ["Cookie is present on first visit"], effort: "S" },
25
+ { title: "Create POST /api/ideas", description: "Accept raw input and optional context", acceptance_criteria: ["Request validation works"], effort: "S" },
26
+ { title: "Implement LLM generation service", description: "Generate strict JSON spec", acceptance_criteria: ["JSON validated with schema"], effort: "M" },
27
+ { title: "Persist idea and tasks", description: "Save generated spec in database", acceptance_criteria: ["Idea and tasks stored"], effort: "S" },
28
+ { title: "Create home page list", description: "Show ideas sorted by hot/new", acceptance_criteria: ["Cards render title, tags, counts"], effort: "S" },
29
+ { title: "Create idea detail page", description: "Render problem, features, tasks", acceptance_criteria: ["All core sections visible"], effort: "M" },
30
+ { title: "Add upvote endpoints", description: "Toggle vote per anon cookie", acceptance_criteria: ["One vote per anon_id"], effort: "S" },
31
+ { title: "Add comments endpoints", description: "Create and list comments", acceptance_criteria: ["Comment count updates"], effort: "S" },
32
+ { title: "Add task claim/status/link endpoints", description: "Claim tasks and attach links", acceptance_criteria: ["Claimant can update task"], effort: "M" },
33
+ ],
34
+ open_questions: [
35
+ "Should submitters be able to edit/delete ideas in V0.1?",
36
+ "Do you want to enable similar-ideas matching now or defer to V0.2?",
37
+ ],
38
+ };
39
+ }
40
+
41
+ function promptForSpec(input: {
42
+ raw_input_text: string;
43
+ target_users?: string;
44
+ platform?: string;
45
+ constraints?: string;
46
+ }): string {
47
+ return [
48
+ "Turn the idea into a buildable product specification JSON.",
49
+ "Return strict JSON only.",
50
+ "Rules:",
51
+ "- 3 to 7 features",
52
+ "- 10 to 20 concrete implementation tasks",
53
+ "- do not hallucinate external integrations unless requested",
54
+ "- place missing details in open_questions",
55
+ "Input:",
56
+ JSON.stringify(input),
57
+ ].join("\n");
58
+ }
59
+
60
+ export async function generateSpec(input: {
61
+ raw_input_text: string;
62
+ target_users?: string;
63
+ platform?: string;
64
+ constraints?: string;
65
+ }): Promise<GeneratedSpec> {
66
+ if (!openai) {
67
+ return fallbackSpec(input.raw_input_text, input.platform, input.target_users);
68
+ }
69
+
70
+ const model = process.env.OPENAI_MODEL || "gpt-4.1-mini";
71
+ const basePrompt = promptForSpec(input);
72
+
73
+ for (let attempt = 0; attempt < 2; attempt += 1) {
74
+ const prompt = attempt === 0 ? basePrompt : `${basePrompt}\nFix output as valid JSON matching required schema.`;
75
+
76
+ const response = await openai.chat.completions.create({
77
+ model,
78
+ temperature: 0.2,
79
+ messages: [
80
+ {
81
+ role: "system",
82
+ content:
83
+ "You are a product requirements assistant. Always output valid JSON only, no markdown.",
84
+ },
85
+ { role: "user", content: prompt },
86
+ ],
87
+ response_format: { type: "json_object" },
88
+ });
89
+
90
+ const content = response.choices[0]?.message?.content;
91
+ if (!content) continue;
92
+
93
+ try {
94
+ const parsed = JSON.parse(content);
95
+ return generatedSpecSchema.parse(parsed);
96
+ } catch {
97
+ continue;
98
+ }
99
+ }
100
+
101
+ return fallbackSpec(input.raw_input_text, input.platform, input.target_users);
102
+ }
lib/prisma.ts ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PrismaClient } from "@prisma/client";
2
+
3
+ declare global {
4
+ // eslint-disable-next-line no-var
5
+ var prisma: PrismaClient | undefined;
6
+ // eslint-disable-next-line no-var
7
+ var dbReadyPromise: Promise<void> | undefined;
8
+ }
9
+
10
+ export const prisma = global.prisma ?? new PrismaClient();
11
+
12
+ if (process.env.NODE_ENV !== "production") {
13
+ global.prisma = prisma;
14
+ }
15
+
16
+ async function bootstrapTables() {
17
+ await prisma.$executeRawUnsafe(`
18
+ CREATE TABLE IF NOT EXISTS Idea (
19
+ id TEXT PRIMARY KEY,
20
+ createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
21
+ createdByAnonId TEXT NOT NULL,
22
+ rawInputText TEXT NOT NULL,
23
+ targetUsers TEXT,
24
+ platform TEXT,
25
+ constraints TEXT,
26
+ title TEXT NOT NULL,
27
+ problemStatement TEXT NOT NULL,
28
+ tags TEXT NOT NULL,
29
+ features TEXT NOT NULL,
30
+ openQuestions TEXT NOT NULL,
31
+ upvotesCount INTEGER NOT NULL DEFAULT 0,
32
+ commentsCount INTEGER NOT NULL DEFAULT 0
33
+ );
34
+ `);
35
+
36
+ await prisma.$executeRawUnsafe(`
37
+ CREATE TABLE IF NOT EXISTS Task (
38
+ id TEXT PRIMARY KEY,
39
+ createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
40
+ ideaId TEXT NOT NULL,
41
+ title TEXT NOT NULL,
42
+ description TEXT,
43
+ acceptance TEXT NOT NULL,
44
+ effort TEXT,
45
+ status TEXT NOT NULL DEFAULT 'OPEN',
46
+ claimedByAnonId TEXT,
47
+ claimedAt DATETIME,
48
+ updatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
49
+ FOREIGN KEY (ideaId) REFERENCES Idea(id) ON DELETE CASCADE
50
+ );
51
+ `);
52
+
53
+ await prisma.$executeRawUnsafe(`
54
+ CREATE TABLE IF NOT EXISTS TaskLink (
55
+ id TEXT PRIMARY KEY,
56
+ taskId TEXT NOT NULL,
57
+ url TEXT NOT NULL,
58
+ label TEXT,
59
+ createdByAnonId TEXT NOT NULL,
60
+ createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
61
+ FOREIGN KEY (taskId) REFERENCES Task(id) ON DELETE CASCADE
62
+ );
63
+ `);
64
+
65
+ await prisma.$executeRawUnsafe(`
66
+ CREATE TABLE IF NOT EXISTS Comment (
67
+ id TEXT PRIMARY KEY,
68
+ ideaId TEXT NOT NULL,
69
+ body TEXT NOT NULL,
70
+ createdByAnonId TEXT NOT NULL,
71
+ createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
72
+ FOREIGN KEY (ideaId) REFERENCES Idea(id) ON DELETE CASCADE
73
+ );
74
+ `);
75
+
76
+ await prisma.$executeRawUnsafe(`
77
+ CREATE TABLE IF NOT EXISTS Vote (
78
+ ideaId TEXT NOT NULL,
79
+ anonId TEXT NOT NULL,
80
+ createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
81
+ PRIMARY KEY (ideaId, anonId),
82
+ FOREIGN KEY (ideaId) REFERENCES Idea(id) ON DELETE CASCADE
83
+ );
84
+ `);
85
+
86
+ await prisma.$executeRawUnsafe(`
87
+ CREATE TABLE IF NOT EXISTS Nickname (
88
+ anonId TEXT PRIMARY KEY,
89
+ nickname TEXT NOT NULL,
90
+ updatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
91
+ );
92
+ `);
93
+
94
+ await prisma.$executeRawUnsafe(`
95
+ CREATE TABLE IF NOT EXISTS SubmissionRateLimit (
96
+ id TEXT PRIMARY KEY,
97
+ anonId TEXT NOT NULL,
98
+ ipAddress TEXT NOT NULL,
99
+ windowStart TEXT NOT NULL,
100
+ count INTEGER NOT NULL DEFAULT 0
101
+ );
102
+ `);
103
+
104
+ await prisma.$executeRawUnsafe(
105
+ `CREATE UNIQUE INDEX IF NOT EXISTS SubmissionRateLimit_key ON SubmissionRateLimit(anonId, ipAddress, windowStart);`
106
+ );
107
+ }
108
+
109
+ export async function ensureDb() {
110
+ if (!global.dbReadyPromise) {
111
+ global.dbReadyPromise = bootstrapTables();
112
+ }
113
+ return global.dbReadyPromise;
114
+ }
lib/spec-schema.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { z } from "zod";
2
+
3
+ export const taskSchema = z.object({
4
+ title: z.string().min(1).max(200),
5
+ description: z.string().max(2000).optional().default(""),
6
+ acceptance_criteria: z.array(z.string().min(1).max(300)).max(8).optional().default([]),
7
+ effort: z.enum(["S", "M", "L"]).optional(),
8
+ });
9
+
10
+ export const generatedSpecSchema = z.object({
11
+ title: z.string().min(1).max(200),
12
+ problem_statement: z.string().min(1).max(2000),
13
+ tags: z.array(z.string().min(1).max(40)).max(10).default([]),
14
+ features: z.array(z.string().min(1).max(300)).min(3).max(7),
15
+ tasks: z.array(taskSchema).min(10).max(20),
16
+ open_questions: z.array(z.string().min(1).max(300)).max(10).default([]),
17
+ });
18
+
19
+ export type GeneratedSpec = z.infer<typeof generatedSpecSchema>;
lib/types.ts ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import type { Idea, Task, TaskLink } from "@prisma/client";
2
+
3
+ export type TaskView = Task & { links: TaskLink[] };
4
+
5
+ export type IdeaView = Idea & {
6
+ tasks: TaskView[];
7
+ };
middleware.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextResponse } from "next/server";
2
+ import type { NextRequest } from "next/server";
3
+
4
+ export function middleware(request: NextRequest) {
5
+ const response = NextResponse.next();
6
+ const anon = request.cookies.get("anon_id")?.value;
7
+
8
+ if (!anon) {
9
+ response.cookies.set("anon_id", crypto.randomUUID(), {
10
+ httpOnly: true,
11
+ sameSite: "lax",
12
+ secure: process.env.NODE_ENV === "production",
13
+ path: "/",
14
+ maxAge: 60 * 60 * 24 * 365,
15
+ });
16
+ }
17
+
18
+ return response;
19
+ }
20
+
21
+ export const config = {
22
+ matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
23
+ };
next-env.d.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ /// <reference types="next" />
2
+ /// <reference types="next/image-types/global" />
3
+ /// <reference path="./.next/types/routes.d.ts" />
4
+
5
+ // NOTE: This file should not be edited
6
+ // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
next.config.ts ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import type { NextConfig } from "next";
2
+
3
+ const nextConfig: NextConfig = {
4
+ experimental: {
5
+ typedRoutes: true,
6
+ },
7
+ };
8
+
9
+ export default nextConfig;
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "demandsolution-codex",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "scripts": {
6
+ "dev": "next dev",
7
+ "build": "next build",
8
+ "start": "next start",
9
+ "lint": "next lint",
10
+ "prisma:generate": "prisma generate",
11
+ "prisma:migrate": "prisma migrate dev --name init"
12
+ },
13
+ "dependencies": {
14
+ "@prisma/client": "^6.4.1",
15
+ "next": "^15.5.12",
16
+ "openai": "^4.80.1",
17
+ "react": "^19.0.0",
18
+ "react-dom": "^19.0.0",
19
+ "zod": "^3.24.1"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^22.10.5",
23
+ "@types/react": "^19.0.2",
24
+ "@types/react-dom": "^19.0.2",
25
+ "autoprefixer": "^10.4.20",
26
+ "postcss": "^8.5.1",
27
+ "prisma": "^6.4.1",
28
+ "tailwindcss": "^3.4.17",
29
+ "typescript": "^5.7.3"
30
+ }
31
+ }
postcss.config.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {},
5
+ },
6
+ };
prisma/schema.prisma ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ generator client {
2
+ provider = "prisma-client-js"
3
+ }
4
+
5
+ datasource db {
6
+ provider = "sqlite"
7
+ url = env("DATABASE_URL")
8
+ }
9
+
10
+ model Idea {
11
+ id String @id @default(uuid())
12
+ createdAt DateTime @default(now())
13
+ createdByAnonId String
14
+ rawInputText String
15
+ targetUsers String?
16
+ platform String?
17
+ constraints String?
18
+ title String
19
+ problemStatement String
20
+ tags String
21
+ features String
22
+ openQuestions String
23
+ upvotesCount Int @default(0)
24
+ commentsCount Int @default(0)
25
+ tasks Task[]
26
+ comments Comment[]
27
+ votes Vote[]
28
+ }
29
+
30
+ model Task {
31
+ id String @id @default(uuid())
32
+ createdAt DateTime @default(now())
33
+ ideaId String
34
+ title String
35
+ description String?
36
+ acceptance String
37
+ effort String?
38
+ status String @default("OPEN")
39
+ claimedByAnonId String?
40
+ claimedAt DateTime?
41
+ updatedAt DateTime @updatedAt
42
+ idea Idea @relation(fields: [ideaId], references: [id], onDelete: Cascade)
43
+ links TaskLink[]
44
+ }
45
+
46
+ model TaskLink {
47
+ id String @id @default(uuid())
48
+ taskId String
49
+ url String
50
+ label String?
51
+ createdByAnonId String
52
+ createdAt DateTime @default(now())
53
+ task Task @relation(fields: [taskId], references: [id], onDelete: Cascade)
54
+ }
55
+
56
+ model Comment {
57
+ id String @id @default(uuid())
58
+ ideaId String
59
+ body String
60
+ createdByAnonId String
61
+ createdAt DateTime @default(now())
62
+ idea Idea @relation(fields: [ideaId], references: [id], onDelete: Cascade)
63
+ }
64
+
65
+ model Vote {
66
+ ideaId String
67
+ anonId String
68
+ createdAt DateTime @default(now())
69
+ idea Idea @relation(fields: [ideaId], references: [id], onDelete: Cascade)
70
+
71
+ @@id([ideaId, anonId])
72
+ }
73
+
74
+ model Nickname {
75
+ anonId String @id
76
+ nickname String
77
+ updatedAt DateTime @updatedAt
78
+ }
79
+
80
+ model SubmissionRateLimit {
81
+ id String @id @default(uuid())
82
+ anonId String
83
+ ipAddress String
84
+ windowStart String
85
+ count Int @default(0)
86
+
87
+ @@unique([anonId, ipAddress, windowStart])
88
+ }
tailwind.config.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Config } from "tailwindcss";
2
+
3
+ const config: Config = {
4
+ content: ["./app/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}"],
5
+ theme: {
6
+ extend: {
7
+ colors: {
8
+ ink: "#141414",
9
+ paper: "#f6f3ea",
10
+ accent: "#0f766e",
11
+ },
12
+ },
13
+ },
14
+ plugins: [],
15
+ };
16
+
17
+ export default config;
tsconfig.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["dom", "dom.iterable", "esnext"],
5
+ "allowJs": false,
6
+ "skipLibCheck": true,
7
+ "strict": true,
8
+ "noEmit": true,
9
+ "esModuleInterop": true,
10
+ "module": "esnext",
11
+ "moduleResolution": "bundler",
12
+ "resolveJsonModule": true,
13
+ "isolatedModules": true,
14
+ "jsx": "preserve",
15
+ "incremental": true,
16
+ "plugins": [{ "name": "next" }],
17
+ "paths": {
18
+ "@/*": ["./*"]
19
+ }
20
+ },
21
+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
22
+ "exclude": ["node_modules"]
23
+ }