-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
93 lines (81 loc) · 3.04 KB
/
route.ts
File metadata and controls
93 lines (81 loc) · 3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { type NextRequest } from 'next/server';
import { z } from 'zod';
import { handleError } from '@/lib/utils/errors.utils';
import { getSession } from '@/lib/utils/auth.utils';
import { assertRecruiterOrAbove } from '@/lib/utils/permissions.utils';
import emailService from '@/lib/services/email.service';
import { prisma } from '@/lib/prisma';
import { AssessmentStatus } from '@/generated/prisma';
const sendAssessmentInvitationSchema = z.object({
positionId: z.string().cuid(),
});
export async function POST(request: NextRequest) {
try {
const session = await getSession();
await assertRecruiterOrAbove(request.headers);
const body = await request.json();
const { positionId } = sendAssessmentInvitationSchema.parse(body);
const position = await prisma.position.findUnique({
where: { id: positionId },
select: { assessmentId: true, orgId: true },
});
if (!position) {
return Response.json({ message: 'Position not found' }, { status: 404 });
}
if (position.orgId !== session.activeOrganizationId) {
return Response.json({ message: 'Unauthorized' }, { status: 403 });
}
if (!position.assessmentId) {
return Response.json(
{ message: 'Position does not have an assessment template assigned' },
{ status: 400 }
);
}
const applications = await prisma.application.findMany({
where: {
positionId,
assessmentStatus: AssessmentStatus.NOT_SENT,
},
include: {
candidate: true,
},
});
const results = [];
for (const application of applications) {
try {
const result = await emailService.sendAssessmentInvitationEmail(
application.candidate.id,
session.activeOrganizationId
);
await prisma.application.update({
where: { id: application.id },
data: { assessmentStatus: AssessmentStatus.NOT_STARTED },
});
results.push({
...result,
applicationId: application.id,
});
} catch (err) {
results.push({
success: false,
message: `Failed to send invitation to ${application.candidate.name}: ${(err as Error).message}`,
candidateName: application.candidate.name,
positionTitle: '',
assessmentId: '',
});
}
}
return Response.json(
{
data: {
totalSent: results.filter((r) => r.success).length,
totalFailed: results.filter((r) => !r.success).length,
results,
},
},
{ status: 200 }
);
} catch (err) {
return handleError(err);
}
}