[057453c] | 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 { EmployeeStatus } 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 | const employees = await prisma.employee.findMany({
|
---|
| 26 | where: {
|
---|
| 27 | tenantId,
|
---|
| 28 | name: { contains: validatedFilters.name, mode: 'insensitive' },
|
---|
| 29 | status: validatedFilters.status
|
---|
| 30 | ? { equals: validatedFilters.status as EmployeeStatus }
|
---|
| 31 | : undefined,
|
---|
| 32 | },
|
---|
| 33 | });
|
---|
| 34 |
|
---|
| 35 | return NextResponse.json(employees);
|
---|
| 36 | } catch (error) {
|
---|
| 37 | console.error('Error fetching employees:', 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, tenantId } = authResult;
|
---|
| 50 |
|
---|
| 51 | const body = await request.json();
|
---|
| 52 | const validatedData = newEmployeeSchema.parse(body);
|
---|
| 53 |
|
---|
| 54 | const employee = await prisma.employee.create({
|
---|
| 55 | data: {
|
---|
| 56 | ...validatedData,
|
---|
| 57 | tenantId,
|
---|
| 58 | },
|
---|
| 59 | });
|
---|
| 60 |
|
---|
| 61 | return NextResponse.json(employee, { status: 201 });
|
---|
| 62 | } catch (error) {
|
---|
| 63 | console.error('Error creating employee:', error);
|
---|
| 64 | return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
---|
| 65 | }
|
---|
| 66 | }
|
---|