Skip to content
Closed
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
115 changes: 115 additions & 0 deletions app/api/routes-d/account/close/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { verifyAuthToken } from '@/lib/auth'

/**
* Grace period before a deletion request is allowed to execute. Keeps the
* door open for support to cancel an accidental request and lines up with
* the typical regulatory window for account-deletion withdrawal.
*/
const DELETION_GRACE_DAYS = 30
const MAX_REASON_LENGTH = 500

type AccountDeletionDelegate = {
findFirst: (args: Record<string, unknown>) => Promise<Record<string, unknown> | null>
create: (args: Record<string, unknown>) => Promise<Record<string, unknown>>
}

function getDeletionDelegate() {
return (prisma as unknown as { accountDeletionRequest: AccountDeletionDelegate }).accountDeletionRequest
}

async function getAuthenticatedUser(request: NextRequest) {
const authToken = request.headers.get('authorization')?.replace('Bearer ', '')
const claims = await verifyAuthToken(authToken || '')

if (!claims) {
return null
}

return prisma.user.findUnique({
where: { privyId: claims.userId },
select: { id: true },
})
}

function normalizeReason(value: unknown): string | null | undefined {
if (value === undefined || value === null) return null
if (typeof value !== 'string') return undefined

const trimmed = value.trim()
if (trimmed.length === 0) return null
if (trimmed.length > MAX_REASON_LENGTH) return undefined

return trimmed
}

export async function POST(request: NextRequest) {
const user = await getAuthenticatedUser(request)
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

let body: unknown
try {
body = await request.json()
} catch {
body = {}
}

const reason = normalizeReason((body as { reason?: unknown } | null | undefined)?.reason)
if (reason === undefined) {
return NextResponse.json(
{ error: `Reason must be at most ${MAX_REASON_LENGTH} characters` },
{ status: 400 },
)
}

const deletionDelegate = getDeletionDelegate()

const existing = await deletionDelegate.findFirst({
where: { userId: user.id, status: 'pending' },
select: { id: true, scheduledAt: true, createdAt: true },
})

if (existing) {
return NextResponse.json(
{
id: existing.id,
status: 'pending',
scheduledAt: existing.scheduledAt,
createdAt: existing.createdAt,
message: 'A deletion request is already pending. Cancel it before raising a new one.',
},
{ status: 409 },
)
}

const scheduledAt = new Date(Date.now() + DELETION_GRACE_DAYS * 24 * 60 * 60 * 1000)

const created = await deletionDelegate.create({
data: {
userId: user.id,
reason,
status: 'pending',
scheduledAt,
},
select: {
id: true,
status: true,
scheduledAt: true,
createdAt: true,
},
})

return NextResponse.json(
{
id: created.id,
status: created.status,
scheduledAt: created.scheduledAt,
createdAt: created.createdAt,
graceDays: DELETION_GRACE_DAYS,
},
{ status: 202 },
)
}
62 changes: 62 additions & 0 deletions app/api/routes-d/billing/plan/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { verifyAuthToken } from '@/lib/auth'
import { logger } from '@/lib/logger'

async function getAuthenticatedUser(request: NextRequest) {
const authToken = request.headers.get('authorization')?.replace('Bearer ', '')
const claims = await verifyAuthToken(authToken || '')

if (!claims) {
return null
}

return prisma.user.findUnique({
where: { privyId: claims.userId },
select: { id: true },
})
}

export async function GET(request: NextRequest) {
try {
const user = await getAuthenticatedUser(request)
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const plan = await prisma.subscription.findFirst({
where: {
userId: user.id,
status: 'active',
},
orderBy: { createdAt: 'desc' },
select: {
id: true,
status: true,
frequency: true,
interval: true,
amount: true,
currency: true,
clientEmail: true,
clientName: true,
description: true,
nextGenerationDate: true,
lastGeneratedAt: true,
createdAt: true,
updatedAt: true,
},
})

return NextResponse.json({
plan: plan
? {
...plan,
amount: Number(plan.amount),
}
: null,
})
} catch (error) {
logger.error({ err: error }, 'Routes D billing plan GET error')
return NextResponse.json({ error: 'Failed to get billing plan' }, { status: 500 })
}
}
90 changes: 90 additions & 0 deletions app/api/routes-d/payout-methods/[id]/default/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { verifyAuthToken } from '@/lib/auth'
import { logger } from '@/lib/logger'

async function getAuthenticatedUser(request: NextRequest) {
const authToken = request.headers.get('authorization')?.replace('Bearer ', '')
const claims = await verifyAuthToken(authToken || '')

if (!claims) {
return null
}

return prisma.user.findUnique({
where: { privyId: claims.userId },
select: { id: true },
})
}

export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const user = await getAuthenticatedUser(request)
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const { id } = await params

const method = await prisma.paymentMethod.findUnique({
where: { id },
select: {
id: true,
userId: true,
type: true,
name: true,
value: true,
isDefault: true,
},
})

if (!method) {
return NextResponse.json({ error: 'Payout method not found' }, { status: 404 })
}

if (method.userId !== user.id) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}

if (method.isDefault) {
return NextResponse.json(
{
payoutMethod: {
id: method.id,
type: method.type,
name: method.name,
value: method.value,
isDefault: true,
},
},
{ status: 200 },
)
}

const [, updatedMethod] = await prisma.$transaction([
prisma.paymentMethod.updateMany({
where: { userId: user.id, isDefault: true },
data: { isDefault: false },
}),
prisma.paymentMethod.update({
where: { id },
data: { isDefault: true },
select: {
id: true,
type: true,
name: true,
value: true,
isDefault: true,
},
}),
])

return NextResponse.json({ payoutMethod: updatedMethod }, { status: 200 })
} catch (error) {
logger.error({ err: error }, 'Routes D payout-methods default PATCH error')
return NextResponse.json({ error: 'Failed to update payout method default' }, { status: 500 })
}
}
69 changes: 69 additions & 0 deletions app/api/routes-d/wallet/pending/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { verifyAuthToken } from '@/lib/auth'
import { logger } from '@/lib/logger'

async function getAuthenticatedUser(request: NextRequest) {
const authToken = request.headers.get('authorization')?.replace('Bearer ', '')
const claims = await verifyAuthToken(authToken || '')

if (!claims) {
return null
}

return prisma.user.findUnique({
where: { privyId: claims.userId },
select: { id: true },
})
}

export async function GET(request: NextRequest) {
try {
const user = await getAuthenticatedUser(request)
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const wallet = await prisma.wallet.findUnique({
where: { userId: user.id },
select: { id: true, address: true },
})

if (!wallet) {
return NextResponse.json({
pending: {
amount: 0,
currency: 'USD',
invoiceCount: 0,
},
})
}

const [pendingInvoices, pendingCount] = await Promise.all([
prisma.invoice.aggregate({
where: {
userId: user.id,
status: 'pending',
},
_sum: { amount: true },
}),
prisma.invoice.count({
where: {
userId: user.id,
status: 'pending',
},
}),
])

return NextResponse.json({
pending: {
amount: Number(pendingInvoices._sum.amount ?? 0),
currency: 'USD',
invoiceCount: pendingCount,
},
})
} catch (error) {
logger.error({ err: error }, 'Routes D wallet pending GET error')
return NextResponse.json({ error: 'Failed to get pending wallet balances' }, { status: 500 })
}
}
Loading
Loading