89 lines
2.2 KiB
TypeScript
89 lines
2.2 KiB
TypeScript
|
|
import { NextRequest, NextResponse } from 'next/server'
|
||
|
|
import { auth } from '@/lib/auth'
|
||
|
|
import { prisma } from '@/lib/prisma'
|
||
|
|
import { UserStatus, Prisma } from '@prisma/client'
|
||
|
|
|
||
|
|
/**
|
||
|
|
* GET /api/v1/admin/customers
|
||
|
|
* List all customers with optional filters
|
||
|
|
*/
|
||
|
|
export async function GET(request: NextRequest) {
|
||
|
|
try {
|
||
|
|
const session = await auth()
|
||
|
|
|
||
|
|
if (!session || session.user.userType !== 'staff') {
|
||
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||
|
|
}
|
||
|
|
|
||
|
|
const searchParams = request.nextUrl.searchParams
|
||
|
|
const status = searchParams.get('status') as UserStatus | null
|
||
|
|
const search = searchParams.get('search')
|
||
|
|
const page = parseInt(searchParams.get('page') || '1')
|
||
|
|
const limit = parseInt(searchParams.get('limit') || '50')
|
||
|
|
|
||
|
|
const where: Prisma.UserWhereInput = {}
|
||
|
|
|
||
|
|
if (status) {
|
||
|
|
where.status = status
|
||
|
|
}
|
||
|
|
|
||
|
|
if (search) {
|
||
|
|
where.OR = [
|
||
|
|
{ email: { contains: search, mode: 'insensitive' } },
|
||
|
|
{ name: { contains: search, mode: 'insensitive' } },
|
||
|
|
{ company: { contains: search, mode: 'insensitive' } },
|
||
|
|
]
|
||
|
|
}
|
||
|
|
|
||
|
|
const [customers, total] = await Promise.all([
|
||
|
|
prisma.user.findMany({
|
||
|
|
where,
|
||
|
|
select: {
|
||
|
|
id: true,
|
||
|
|
email: true,
|
||
|
|
name: true,
|
||
|
|
company: true,
|
||
|
|
status: true,
|
||
|
|
createdAt: true,
|
||
|
|
subscriptions: {
|
||
|
|
select: {
|
||
|
|
id: true,
|
||
|
|
plan: true,
|
||
|
|
tier: true,
|
||
|
|
status: true,
|
||
|
|
},
|
||
|
|
take: 1,
|
||
|
|
orderBy: { createdAt: 'desc' },
|
||
|
|
},
|
||
|
|
_count: {
|
||
|
|
select: {
|
||
|
|
orders: true,
|
||
|
|
subscriptions: true,
|
||
|
|
},
|
||
|
|
},
|
||
|
|
},
|
||
|
|
orderBy: { createdAt: 'desc' },
|
||
|
|
skip: (page - 1) * limit,
|
||
|
|
take: limit,
|
||
|
|
}),
|
||
|
|
prisma.user.count({ where }),
|
||
|
|
])
|
||
|
|
|
||
|
|
return NextResponse.json({
|
||
|
|
customers,
|
||
|
|
pagination: {
|
||
|
|
page,
|
||
|
|
limit,
|
||
|
|
total,
|
||
|
|
totalPages: Math.ceil(total / limit),
|
||
|
|
},
|
||
|
|
})
|
||
|
|
} catch (error) {
|
||
|
|
console.error('Error listing customers:', error)
|
||
|
|
return NextResponse.json(
|
||
|
|
{ error: 'Failed to list customers' },
|
||
|
|
{ status: 500 }
|
||
|
|
)
|
||
|
|
}
|
||
|
|
}
|