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

// GET /api/routes-b/analytics/invoices — invoice counts grouped by status
export async function GET(request: NextRequest) {
try {
const authToken = request.headers.get('authorization')?.replace('Bearer ', '')
const claims = await verifyAuthToken(authToken || '')
if (!claims) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const user = await prisma.user.findUnique({ where: { privyId: claims.userId } })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const [grouped, totals] = await Promise.all([
prisma.invoice.groupBy({
by: ['status'],
where: { userId: user.id },
_count: { id: true },
}),
prisma.invoice.aggregate({
where: { userId: user.id },
_count: { id: true },
_sum: { amount: true },
}),
])

const counts = { pending: 0, paid: 0, overdue: 0, cancelled: 0 }
for (const row of grouped) {
const status = row.status as keyof typeof counts
if (status in counts) {
counts[status] = row._count.id
}
}

return NextResponse.json({
invoices: {
total: totals._count.id,
pending: counts.pending,
paid: counts.paid,
overdue: counts.overdue,
cancelled: counts.cancelled,
totalInvoiced: totals._sum.amount ?? 0,
}
})
} catch (error) {
console.error('Error fetching invoice analytics:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}
93 changes: 93 additions & 0 deletions app/api/routes-b/dashboard/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { verifyAuthToken } from '@/lib/auth'

// GET /api/routes-b/dashboard — combined dashboard summary
export async function GET(request: NextRequest) {
try {
const authToken = request.headers.get('authorization')?.replace('Bearer ', '')
const claims = await verifyAuthToken(authToken || '')
if (!claims) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const user = await prisma.user.findUnique({ where: { privyId: claims.userId } })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const now = new Date()
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)

const [invoiceStats, totalEarned, thisMonthEarned, recentTxns] = await Promise.all([
prisma.invoice.groupBy({
by: ['status'],
where: { userId: user.id },
_count: { id: true },
}),
prisma.transaction.aggregate({
where: { userId: user.id, type: 'payment', status: 'completed' },
_sum: { amount: true },
}),
prisma.transaction.aggregate({
where: {
userId: user.id,
type: 'payment',
status: 'completed',
createdAt: { gte: startOfMonth },
},
_sum: { amount: true },
}),
prisma.transaction.findMany({
where: { userId: user.id },
orderBy: { createdAt: 'desc' },
take: 5,
select: {
id: true,
type: true,
amount: true,
currency: true,
createdAt: true,
},
}),
])

// Build invoice status counts
const invoiceCounts = { pending: 0, paid: 0, overdue: 0, cancelled: 0 }
for (const row of invoiceStats) {
const status = row.status as keyof typeof invoiceCounts
if (status in invoiceCounts) {
invoiceCounts[status] = row._count.id
}
}

const totalInvoices = Object.values(invoiceCounts).reduce((a, b) => a + b, 0)

return NextResponse.json({
summary: {
invoices: {
total: totalInvoices,
pending: invoiceCounts.pending,
paid: invoiceCounts.paid,
overdue: invoiceCounts.overdue,
cancelled: invoiceCounts.cancelled,
},
earnings: {
totalEarned: totalEarned._sum.amount ?? 0,
thisMonth: thisMonthEarned._sum.amount ?? 0,
currency: 'USDC',
},
recentTransactions: recentTxns.map((tx) => ({
id: tx.id,
type: tx.type,
amount: tx.amount,
currency: tx.currency,
createdAt: tx.createdAt,
})),
},
})
} catch (error) {
console.error('Error fetching dashboard:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}
68 changes: 68 additions & 0 deletions app/api/routes-b/invoices/[id]/duplicate/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { verifyAuthToken } from '@/lib/auth'
import { generateInvoiceNumber } from '@/lib/utils'

// POST /api/routes-b/invoices/[id]/duplicate — duplicate an invoice
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const authToken = request.headers.get('authorization')?.replace('Bearer ', '')
const claims = await verifyAuthToken(authToken || '')
if (!claims) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const user = await prisma.user.findUnique({ where: { privyId: claims.userId } })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const { id } = params

const sourceInvoice = await prisma.invoice.findUnique({
where: { id },
})

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

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

const newNumber = generateInvoiceNumber()
const baseUrl = process.env.NEXT_PUBLIC_APP_URL || `https://${request.headers.get('host')}`
const paymentLink = `${baseUrl}/pay/${newNumber}`

const newInvoice = await prisma.invoice.create({
data: {
userId: user.id,
invoiceNumber: newNumber,
clientEmail: sourceInvoice.clientEmail,
clientName: sourceInvoice.clientName,
description: sourceInvoice.description,
amount: sourceInvoice.amount,
currency: sourceInvoice.currency,
status: 'pending',
paymentLink,
},
select: {
id: true,
invoiceNumber: true,
clientEmail: true,
amount: true,
status: true,
paymentLink: true,
},
})

return NextResponse.json(newInvoice, { status: 201 })
} catch (error) {
console.error('Error duplicating invoice:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}
62 changes: 62 additions & 0 deletions app/api/routes-b/invoices/overdue/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'

// GET /api/routes-b/invoices/overdue — list overdue invoices
export async function GET(request: NextRequest) {
try {
const authToken = request.headers.get('authorization')?.replace('Bearer ', '')
const claims = await verifyAuthToken(authToken || '')
if (!claims) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const user = await prisma.user.findUnique({ where: { privyId: claims.userId } })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const now = new Date()

const invoices = await prisma.invoice.findMany({
where: {
userId: user.id,
status: 'pending',
dueDate: { not: null, lt: now },
},
orderBy: { dueDate: 'asc' },
select: {
id: true,
invoiceNumber: true,
clientName: true,
clientEmail: true,
amount: true,
dueDate: true,
},
})

const overdueInvoices = invoices.map((invoice) => {
const daysOverdue = Math.floor(
(now.getTime() - (invoice.dueDate?.getTime() || 0)) / (1000 * 60 * 60 * 24)
)

return {
id: invoice.id,
invoiceNumber: invoice.invoiceNumber,
clientName: invoice.clientName,
clientEmail: invoice.clientEmail,
amount: invoice.amount,
dueDate: invoice.dueDate,
daysOverdue,
}
})

return NextResponse.json({
invoices: overdueInvoices,
total: overdueInvoices.length,
})
} catch (error) {
console.error('Error fetching overdue invoices:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}