Skip to content
Draft
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
64 changes: 43 additions & 21 deletions app/api/analyses/[id]/analyze/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
import { generateText } from 'ai'
import { getCreditBalance, deductCredits, CREDITS } from '@/lib/credits'
import { getCreditBalance, deductCredits, refundCredits, CREDITS } from '@/lib/credits'
import { getCurrentUser } from '@/lib/auth'

const model = 'openai/gpt-4-turbo'

Expand All @@ -20,19 +21,26 @@ interface AppSuggestion {
}

export async function POST(request: NextRequest) {
let chargedUserId: string | null = null
let chargedMetadata: Record<string, unknown> | null = null

try {
const { analysisId, selectedRepos, userId } = (await request.json()) as {
const { analysisId, selectedRepos } = (await request.json()) as {
analysisId: string
selectedRepos: SelectedRepository[]
userId: string
}

// Check credit balance before proceeding
if (!userId) {
return NextResponse.json({ error: 'User ID required' }, { status: 401 })
const user = await getCurrentUser()
if (!user) {
return NextResponse.json({ error: 'Sign in with GitHub to analyze repositories.' }, { status: 401 })
}

if (!analysisId || !Array.isArray(selectedRepos)) {
return NextResponse.json({ error: 'Missing required analysis data' }, { status: 400 })
}

const currentBalance = await getCreditBalance(userId)
// Check and deduct from the authenticated user only.
const currentBalance = await getCreditBalance(user.id)
if (currentBalance < CREDITS.ANALYSIS_COST) {
return NextResponse.json(
{
Expand All @@ -45,6 +53,26 @@ export async function POST(request: NextRequest) {
)
}

chargedMetadata = {
analysisId,
selectedRepos: selectedRepos.map((r) => r.name),
}
const deductResult = await deductCredits(user.id, CREDITS.ANALYSIS_COST, 'analysis', chargedMetadata)

if (!deductResult.success) {
const latestBalance = await getCreditBalance(user.id)
return NextResponse.json(
{
error: 'Insufficient credits',
required: CREDITS.ANALYSIS_COST,
available: latestBalance,
message: deductResult.error ?? 'Not enough credits for analysis.',
},
{ status: 402 }
)
}
chargedUserId = user.id

// Get all repo files from database
const filesByRepo: Record<string, RepositoryTreeFile[]> = {}

Expand Down Expand Up @@ -94,20 +122,6 @@ Return as JSON array of app suggestions. Focus on practical, buildable applicati
console.error('Failed to parse AI response:', e)
}

// Deduct credits for successful analysis
const deductResult = await deductCredits(userId, CREDITS.ANALYSIS_COST, 'analysis', {
analysisId,
selectedRepos: selectedRepos.map((r) => r.name),
})

if (!deductResult.success) {
console.error('Failed to deduct credits:', deductResult.error)
return NextResponse.json(
{ error: 'Failed to process analysis' },
{ status: 500 }
)
}

const newBalance = deductResult.transaction?.balance_after || 0

return NextResponse.json({
Expand All @@ -120,6 +134,14 @@ Return as JSON array of app suggestions. Focus on practical, buildable applicati
})
} catch (error) {
console.error('Analysis error:', error)
if (chargedUserId) {
await refundCredits(chargedUserId, CREDITS.ANALYSIS_COST, 'Legacy analysis failed', {
...(chargedMetadata ?? {}),
error: error instanceof Error ? error.message : String(error),
}).catch((refundError: unknown) => {
console.error('Failed to refund credits after analysis error:', refundError)
})
}
return NextResponse.json({ error: 'Failed to analyze repositories' }, { status: 500 })
}
}
Expand Down
96 changes: 70 additions & 26 deletions app/api/build-app/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ interface BuildAppRequest {
>
}

async function readApiError(res: Response, fallback: string): Promise<string> {
try {
const body = (await res.json()) as { message?: unknown; error?: unknown }
const message = typeof body.message === 'string' ? body.message : body.error
return typeof message === 'string' && message.trim() ? message : fallback
} catch {
return fallback
}
}

/** Generate a single file's content using Claude */
async function generateSingleFile(
blueprint: BuildAppRequest['blueprint'],
Expand Down Expand Up @@ -56,20 +66,27 @@ Just the file content itself, ready to save.`

/** Build the list of all files to generate */
function getFilesToGenerate(blueprint: BuildAppRequest['blueprint']): Array<{ path: string; purpose: string }> {
const files: Array<{ path: string; purpose: string }> = []
const files = new Map<string, { path: string; purpose: string }>()
const addFile = (path: string, purpose: string) => {
const normalizedPath = path.trim()
if (!normalizedPath || files.has(normalizedPath)) {
return
}
files.set(normalizedPath, { path: normalizedPath, purpose })
}

// Missing files from the blueprint
for (const f of blueprint.missing_files) {
files.push({ path: f.name, purpose: f.purpose })
addFile(f.name, f.purpose)
}

// Standard project files
files.push({ path: 'README.md', purpose: 'Comprehensive setup, usage, and API documentation' })
files.push({ path: 'package.json', purpose: 'Project dependencies and scripts for the tech stack' })
files.push({ path: '.env.example', purpose: 'All required environment variables with placeholder values' })
files.push({ path: '.gitignore', purpose: 'Gitignore file appropriate for this stack' })
addFile('README.md', 'Comprehensive setup, usage, and API documentation')
addFile('package.json', 'Project dependencies and scripts for the tech stack')
addFile('.env.example', 'All required environment variables with placeholder values')
addFile('.gitignore', 'Gitignore file appropriate for this stack')

return files
return Array.from(files.values())
}

async function createGitHubRepo(
Expand All @@ -88,14 +105,13 @@ async function createGitHubRepo(
body: JSON.stringify({
name: repoName,
description,
private: false,
private: true,
auto_init: false,
}),
})

if (!res.ok) {
const err = (await res.json()) as { message?: string }
throw new Error(err.message ?? 'Failed to create GitHub repository')
throw new Error(await readApiError(res, 'Failed to create GitHub repository'))
}

const repo = (await res.json()) as { html_url: string }
Expand Down Expand Up @@ -127,8 +143,7 @@ async function pushFileToGitHub(
)

if (!res.ok) {
const err = (await res.json()) as { message?: string }
console.warn(`[build-app] Failed to push ${path}: ${err.message}`)
throw new Error(await readApiError(res, `Failed to push ${path} to GitHub`))
}
}

Expand All @@ -152,12 +167,7 @@ async function createGitLabProject(
})

if (!res.ok) {
const err = (await res.json()) as { message?: string | Record<string, string[]> }
const msg =
typeof err.message === 'string'
? err.message
: JSON.stringify(err.message)
throw new Error(msg ?? 'Failed to create GitLab project')
throw new Error(await readApiError(res, 'Failed to create GitLab project'))
}

return res.json() as Promise<{ id: number; web_url: string; default_branch: string }>
Expand Down Expand Up @@ -189,8 +199,7 @@ async function pushFileToGitLab(
)

if (!res.ok) {
const err = (await res.json()) as { message?: string }
console.warn(`[build-app] Failed to push ${path} to GitLab: ${err.message}`)
throw new Error(await readApiError(res, `Failed to push ${path} to GitLab`))
}
}

Expand Down Expand Up @@ -223,12 +232,29 @@ export async function POST(request: NextRequest) {
const body = (await request.json()) as BuildAppRequest
const { platform, repoName, blueprint } = body

if (platform !== 'github' && platform !== 'gitlab') {
send({ step: 'error', message: 'Choose GitHub or GitLab before building.' })
controller.close()
return
}

if (!repoName?.trim()) {
send({ step: 'error', message: 'Repository name is required.' })
controller.close()
return
}

if (
!blueprint ||
!Array.isArray(blueprint.technologies) ||
!Array.isArray(blueprint.existing_files) ||
!Array.isArray(blueprint.missing_files)
) {
send({ step: 'error', message: 'Blueprint data is incomplete. Re-run the analysis before building.' })
controller.close()
return
}

const cleanRepoName = repoName.trim().replace(/\s+/g, '-').toLowerCase()

// Step 1 — determine files to generate
Expand Down Expand Up @@ -284,15 +310,32 @@ export async function POST(request: NextRequest) {
try {
content = await generateSingleFile(blueprint, path, purpose, user.id)
} catch (e) {
console.warn(`[build-app] Failed to generate ${path}:`, e)
content = `# Error generating ${path}\n# ${e instanceof Error ? e.message : String(e)}\n`
const message = e instanceof Error ? e.message : String(e)
console.error(`[build-app] Failed to generate ${path}:`, e)
send({
step: 'error',
message: `Failed to generate ${path}: ${message}. The repository may be incomplete; no success event was emitted.`,
repoUrl,
})
return
}

// Push to platform
if (platform === 'github') {
await pushFileToGitHub(accessToken, user.github_username, cleanRepoName, path, content)
} else if (gitlabProjectId !== null) {
await pushFileToGitLab(accessToken, gitlabProjectId, gitlabBranch, path, content)
try {
if (platform === 'github') {
await pushFileToGitHub(accessToken, user.github_username, cleanRepoName, path, content)
} else if (gitlabProjectId !== null) {
await pushFileToGitLab(accessToken, gitlabProjectId, gitlabBranch, path, content)
}
} catch (e) {
const message = e instanceof Error ? e.message : String(e)
console.error(`[build-app] Failed to push ${path}:`, e)
send({
step: 'error',
message: `Failed to push ${path}: ${message}. The repository may be incomplete; no success event was emitted.`,
repoUrl,
})
return
}

pushed++
Expand All @@ -301,6 +344,7 @@ export async function POST(request: NextRequest) {
message: `Pushed ${pushed}/${total} files`,
current: pushed,
total,
repoUrl,
path,
preview: content.slice(0, 600),
})
Expand Down
Loading
Loading