1 | import { NextRequest, NextResponse } from 'next/server';
|
---|
2 | import { employeeTableFiltersSchema, newEmployeeSchema } from 'src/schemas';
|
---|
3 | import prisma from 'src/lib/prisma';
|
---|
4 | import { authenticateRequest } from 'src/lib/auth-middleware';
|
---|
5 | import { Prisma } 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, tenantId } = authResult;
|
---|
15 |
|
---|
16 | const searchParams = request.nextUrl.searchParams;
|
---|
17 | const filters = {
|
---|
18 | name: searchParams.get('name') || '',
|
---|
19 | status: searchParams.get('status') || '',
|
---|
20 | };
|
---|
21 |
|
---|
22 | // Validate filters
|
---|
23 | const validatedFilters = employeeTableFiltersSchema.parse(filters);
|
---|
24 |
|
---|
25 | // Replace Prisma query with raw SQL
|
---|
26 | const employees = await prisma.$queryRaw`
|
---|
27 | SELECT * FROM "Employee"
|
---|
28 | WHERE "tenantId" = ${tenantId}
|
---|
29 | AND LOWER(name) LIKE LOWER(${`%${validatedFilters.name}%`})
|
---|
30 | ${
|
---|
31 | validatedFilters.status
|
---|
32 | ? Prisma.sql`AND status = ${validatedFilters.status}:::"EmployeeStatus"`
|
---|
33 | : Prisma.sql`AND TRUE`
|
---|
34 | }
|
---|
35 | `;
|
---|
36 |
|
---|
37 | return NextResponse.json(employees);
|
---|
38 | } catch (error) {
|
---|
39 | console.error('Error fetching employees:', error);
|
---|
40 | return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
---|
41 | }
|
---|
42 | }
|
---|
43 |
|
---|
44 | export async function POST(request: NextRequest) {
|
---|
45 | try {
|
---|
46 | // Authenticate the request
|
---|
47 | const authResult = await authenticateRequest(request);
|
---|
48 | if (authResult instanceof NextResponse) {
|
---|
49 | return authResult;
|
---|
50 | }
|
---|
51 | const { userId, tenantId } = authResult;
|
---|
52 |
|
---|
53 | const body = await request.json();
|
---|
54 | const validatedData = newEmployeeSchema.parse(body);
|
---|
55 |
|
---|
56 | const employee = await prisma.employee.create({
|
---|
57 | data: {
|
---|
58 | ...validatedData,
|
---|
59 | tenantId,
|
---|
60 | },
|
---|
61 | });
|
---|
62 |
|
---|
63 | return NextResponse.json(employee, { status: 201 });
|
---|
64 | } catch (error) {
|
---|
65 | console.error('Error creating employee:', error);
|
---|
66 | return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
---|
67 | }
|
---|
68 | }
|
---|