1 | import { NextRequest, NextResponse } from 'next/server';
|
---|
2 | import { customerTableFiltersSchema, newCustomerSchema } from 'src/schemas';
|
---|
3 | import prisma from 'src/lib/prisma';
|
---|
4 | import { authenticateRequest } from 'src/lib/auth-middleware';
|
---|
5 | import { CustomerStatus } from '@prisma/client';
|
---|
6 |
|
---|
7 | export async function GET(request: NextRequest) {
|
---|
8 | try {
|
---|
9 | // Authenticate the request
|
---|
10 | const authResult = await authenticateRequest(request);
|
---|
11 | if (authResult instanceof NextResponse) {
|
---|
12 | return authResult;
|
---|
13 | }
|
---|
14 | const { userId } = authResult;
|
---|
15 |
|
---|
16 | const searchParams = request.nextUrl.searchParams;
|
---|
17 | const filters = {
|
---|
18 | name: searchParams.get('name') || '',
|
---|
19 | role: searchParams.getAll('role'),
|
---|
20 | status: searchParams.get('status') || '',
|
---|
21 | };
|
---|
22 |
|
---|
23 | // Validate filters
|
---|
24 | const validatedFilters = customerTableFiltersSchema.parse(filters);
|
---|
25 |
|
---|
26 | const customers = await prisma.client.findMany({
|
---|
27 | where: {
|
---|
28 | name: { contains: validatedFilters.name, mode: 'insensitive' },
|
---|
29 | status: validatedFilters.status
|
---|
30 | ? { equals: validatedFilters.status as CustomerStatus }
|
---|
31 | : undefined,
|
---|
32 | },
|
---|
33 | });
|
---|
34 | console.log('customers', customers);
|
---|
35 |
|
---|
36 | return NextResponse.json(customers);
|
---|
37 | } catch (error) {
|
---|
38 | return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
---|
39 | }
|
---|
40 | }
|
---|
41 |
|
---|
42 | export async function POST(request: NextRequest) {
|
---|
43 | try {
|
---|
44 | // Authenticate the request
|
---|
45 | const authResult = await authenticateRequest(request);
|
---|
46 | if (authResult instanceof NextResponse) {
|
---|
47 | return authResult;
|
---|
48 | }
|
---|
49 | const { userId } = authResult;
|
---|
50 |
|
---|
51 | const body = await request.json();
|
---|
52 | const validatedData = newCustomerSchema.parse(body);
|
---|
53 | console.log('validatedData', validatedData);
|
---|
54 |
|
---|
55 | const customer = await prisma.client.create({
|
---|
56 | data: {
|
---|
57 | ...validatedData,
|
---|
58 | // userId,
|
---|
59 | },
|
---|
60 | });
|
---|
61 |
|
---|
62 | return NextResponse.json(customer, { status: 201 });
|
---|
63 | } catch (error) {
|
---|
64 | console.error('Error creating customer:', error);
|
---|
65 | return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
---|
66 | }
|
---|
67 | }
|
---|