Skip to content
Merged

Dev 6 #124

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 6 additions & 45 deletions app/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,64 +226,25 @@ export async function submitEmployeeFeedback(formData: FormData) {
}
});

// 🟢 NEW: Close the TNI/Nomination loop and add to Training History upon Employee Feedback
if (updatedEnrollment.session?.nominationBatchId) {
// 🟢 NEW: Update the Training History with the final L3 rating
if (updatedEnrollment.session?.id) {
let effectiveEmpId = updatedEnrollment.empId;
let empLocation = null;
let progCategory = null;

// 1. Get Employee Details
if (!effectiveEmpId) {
const emp = await db.employee.findUnique({
where: { email: updatedEnrollment.employeeEmail },
select: { id: true, location: true }
select: { id: true }
});
effectiveEmpId = emp?.id ?? null;
empLocation = emp?.location ?? null;
} else {
const emp = await db.employee.findUnique({
where: { id: effectiveEmpId },
select: { location: true }
});
empLocation = emp?.location ?? null;
}

// 2. Get Program Category
const prog = await db.program.findUnique({
where: { name: updatedEnrollment.session.programName },
select: { category: true }
});
progCategory = prog?.category ?? null;

// 3. Calculate Training Days
const start = new Date(updatedEnrollment.session.startDate);
const end = new Date(updatedEnrollment.session.endDate);
const trainingDays = Math.ceil((end.getTime() - start.getTime()) / (1000 * 3600 * 24)) + 1;

if (effectiveEmpId) {
// A. Close the TNI Loop
await db.nomination.updateMany({
// Update existing Training History with L3 rating
await db.trainingHistory.updateMany({
where: {
empId: effectiveEmpId,
batchId: updatedEnrollment.session.nominationBatchId
sessionId: updatedEnrollment.session.id
},
data: { status: 'Completed' }
});

// B. Add to Training History
await db.trainingHistory.create({
data: {
empId: effectiveEmpId,
employeeName: updatedEnrollment.employeeName,
programName: updatedEnrollment.session.programName,
startDate: updatedEnrollment.session.startDate,
endDate: updatedEnrollment.session.endDate,
trainingDays: trainingDays > 0 ? trainingDays : null,
location: updatedEnrollment.session.location || empLocation,
progCategory: progCategory,
source: 'SYSTEM',
sessionId: updatedEnrollment.session.id,
trainerName: updatedEnrollment.session.trainerName,
averageRating: average
}
});
Expand Down
193 changes: 193 additions & 0 deletions app/actions/calendar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
'use server';

import { db } from '@/lib/prisma';
import { revalidatePath, revalidateTag } from 'next/cache';
import { auth } from '@/auth';

// 1. Fetch Calendar Events (Admin & User)
export async function getCalendarEvents(forUser = false) {
const where: any = { publishToCalendar: true };
// Users generally only see "Forming" batches they can join
// Admins might want to see Scheduled ones too if we want a unified calendar
if (forUser) {
where.status = 'Forming';
}

return await db.nominationBatch.findMany({
where,
include: {
program: true,
nominations: true,
trainingSession: true
},
orderBy: { proposedStartDate: 'asc' }
});
}

// 2. Create Pre-Scheduled Event (Admin)
export async function createCalendarEvent(formData: FormData) {
const session = await auth();
if (!session?.user?.email) return { error: "Unauthorized" };

const programId = formData.get('programId') as string;
const proposedStartDate = formData.get('proposedStartDate') as string;
const proposedEndDate = formData.get('proposedEndDate') as string;
const proposedTrainer = formData.get('proposedTrainer') as string;
const proposedLocation = formData.get('proposedLocation') as string;
const capacity = formData.get('capacity') as string;

if (!programId || !proposedStartDate || !proposedEndDate) {
return { error: 'Missing required fields' };
}

try {
const program = await db.program.findUnique({ where: { id: programId } });
if (!program) return { error: 'Program not found' };

await db.nominationBatch.create({
data: {
name: `${program.name} - Planned Event`,
programId,
status: 'Forming',
proposedStartDate: new Date(proposedStartDate),
proposedEndDate: new Date(proposedEndDate),
proposedTrainer: proposedTrainer || null,
proposedLocation: proposedLocation || null,
capacity: capacity ? parseInt(capacity) : 20,
publishToCalendar: true
}
});

revalidateTag('sessions-list', 'max');
revalidatePath('/admin/sessions');
return { success: true };
} catch (error) {
console.error('Create Calendar Event Error:', error);
return { error: 'Failed to create calendar event' };
}
}

// 3. Confirm Event and generate TrainingSession (Admin)
export async function confirmCalendarEvent(batchId: string, formData: FormData) {
const session = await auth();
if (!session?.user?.email) return { error: "Unauthorized" };

const trainerName = formData.get('trainerName') as string;
const location = formData.get('location') as string;
const startTime = formData.get('startTime') as string || "8:30 am";
const endTime = formData.get('endTime') as string || "6:00 pm";

try {
const batch = await db.nominationBatch.findUnique({
where: { id: batchId },
include: { program: true }
});

if (!batch || !batch.proposedStartDate || !batch.proposedEndDate) {

Check warning on line 86 in app/actions/calendar.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer using an optional chain expression instead, as it's more concise and easier to read.

See more on https://sonarcloud.io/project/issues?id=DRAGOR75_TEIPL-Training-Portal&issues=AZ7Uycco9vjCgjba9LrH&open=AZ7Uycco9vjCgjba9LrH&pullRequest=124
return { error: 'Invalid batch or missing proposed dates' };
}

// Generate the final TrainingSession
const assessmentDate = new Date(batch.proposedEndDate.getTime() + 20 * 24 * 60 * 60 * 1000);

await db.trainingSession.create({
data: {
programName: batch.program.name,
trainerName,
startDate: batch.proposedStartDate,
endDate: batch.proposedEndDate,
startTime,
endTime,
location,
topics: batch.program.objectives,
assessmentDate,
feedbackCreationDate: assessmentDate,
nominationBatchId: batch.id
}
});

// Update Batch Status
await db.nominationBatch.update({
where: { id: batch.id },
data: {
status: 'Scheduled',
publishToCalendar: false // Hide from "Upcoming/Forming" calendar view
}
});

revalidateTag('sessions-list', 'max');
revalidateTag('session-details', 'max');
revalidatePath('/admin/sessions');
return { success: true };
} catch (error) {
console.error('Confirm Calendar Event Error:', error);
return { error: 'Failed to confirm event' };
}
}

// 4. Delete/Cancel Event (Admin)
export async function cancelCalendarEvent(batchId: string) {
const session = await auth();
if (!session?.user?.email) return { error: "Unauthorized" };

try {
await db.nominationBatch.delete({
where: { id: batchId }
});

revalidateTag('sessions-list', 'max');
revalidatePath('/admin/sessions');
return { success: true };
} catch (error) {
console.error('Cancel Calendar Event Error:', error);
return { error: 'Failed to cancel event' };
}
}

// 5. Self-Nominate into Calendar Event (Employee)
export async function selfNominateCalendar(batchId: string, empId: string, justification: string) {
try {
const batch = await db.nominationBatch.findUnique({
where: { id: batchId },
include: { program: true }
});

if (!batch) return { error: 'Event not found' };
if (batch.status !== 'Forming') return { error: 'This event is no longer accepting self-nominations' };

// Check if already nominated for this specific batch
const existing = await db.nomination.findFirst({
where: { empId, batchId }
});

if (existing) return { error: 'You are already nominated for this event' };

// Check Capacity
const currentCount = await db.nomination.count({ where: { batchId } });
if (batch.capacity && currentCount >= batch.capacity) {
return { error: 'This event is full' };
}

// Create Nomination mapped to the batch
await db.nomination.create({
data: {
empId,
programId: batch.programId,
batchId,
status: 'Pending', // Pending admin/manager review (or could be 'Batched' if auto-approved)
source: 'CALENDAR',
justification: justification || 'Self-nominated from calendar',
managerApprovalStatus: 'Pending' // Still requires manager approval like regular TNI
}
});

// Trigger standard manager approval email logic if desired
// (Could reuse logic from tni.ts)

revalidateTag('employee-profile', 'max');
return { success: true };
} catch (error) {
console.error('Self Nominate Error:', error);
return { error: 'Failed to submit nomination' };
}
}
62 changes: 62 additions & 0 deletions app/actions/delete-session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
'use server';

import { db } from '@/lib/prisma';
import { revalidatePath, revalidateTag } from 'next/cache';
import { auth } from '@/auth';

export async function deleteTrainingSession(sessionId: string) {
const session = await auth();
if (!session?.user?.email && process.env.NODE_ENV !== 'development') {
return { success: false, error: 'Unauthorized' };
}

try {
const trainingSession = await db.trainingSession.findUnique({
where: { id: sessionId }
});

if (!trainingSession) {
return { success: false, error: 'Session not found.' };
}

const batchId = trainingSession.nominationBatchId;

// If there's a batch tied to it, we revert its nominations and delete the batch
if (batchId) {
// Revert all nominations in this batch back to the pending pool
await db.nomination.updateMany({
where: { batchId },
data: {
status: 'Pending',
managerApprovalStatus: 'Approved',
batchId: null
}
});

// Delete the training session first due to relation
await db.trainingSession.delete({
where: { id: sessionId }
});

// Delete the underlying batch
await db.nominationBatch.delete({
where: { id: batchId }
});
} else {
// No batch found, just delete the session
await db.trainingSession.delete({
where: { id: sessionId }
});
}

revalidatePath('/admin/sessions');
revalidatePath('/admin/tni-dashboard');
// @ts-ignore
revalidateTag('sessions-list');

return { success: true };
} catch (error: any) {
console.error('Failed to delete training session:', error);
return { success: false, error: error.message || 'Failed to delete scheduled session.' };
}
}
53 changes: 52 additions & 1 deletion app/actions/enrollment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { revalidatePath } from "next/cache";
import { sendFeedbackAcknowledgmentEmail } from "@/lib/email";

export async function selfEnroll(formData: FormData) {

Check failure on line 8 in app/actions/enrollment.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=DRAGOR75_TEIPL-Training-Portal&issues=AZ7UycdH9vjCgjba9LrL&open=AZ7UycdH9vjCgjba9LrL&pullRequest=124
const sessionId = formData.get('sessionId') as string;
const empId = formData.get('empId') as string;

Expand All @@ -17,7 +17,15 @@
// 1. Fetch Session to check walk-in rules
const session = await db.trainingSession.findUnique({
where: { id: sessionId },
select: { programName: true, allowWalkIns: true }
select: {
programName: true,
allowWalkIns: true,
nominationBatchId: true,
startDate: true,
endDate: true,
trainerName: true,
location: true
}
});

if (!session) throw new Error("Invalid Session");
Expand Down Expand Up @@ -86,6 +94,49 @@
create: data
});

// 4.5. Close TNI Loop & Create Training History (Moved from 30-day feedback)
if (empId !== 'WALKIN' && session.nominationBatchId) {
let empLocation = null;
const emp = await db.employee.findUnique({ where: { id: empId }, select: { location: true } });
empLocation = emp?.location;

const prog = await db.program.findUnique({ where: { name: session.programName }, select: { category: true } });
const progCategory = prog?.category ?? null;

const start = new Date(session.startDate);
const end = new Date(session.endDate);
const trainingDays = Math.ceil((end.getTime() - start.getTime()) / (1000 * 3600 * 24)) + 1;

// Mark Nomination as Completed
await db.nomination.updateMany({
where: { empId: empId, batchId: session.nominationBatchId },
data: { status: 'Completed' }
});

// Create Training History if it doesn't exist
const existingHistory = await db.trainingHistory.findFirst({
where: { empId: empId, sessionId: sessionId }
});

if (!existingHistory) {
await db.trainingHistory.create({
data: {
empId: empId,
employeeName: finalName,
programName: session.programName,
startDate: session.startDate,
endDate: session.endDate,
trainingDays: trainingDays > 0 ? trainingDays : null,
location: session.location || empLocation,
progCategory: progCategory,
source: 'SYSTEM',
sessionId: sessionId,
trainerName: session.trainerName
}
});
}
}

// 5. Send Acknowledgment Email (Non-blocking)
if (formData.get('isAdmin') !== 'true') {
await sendFeedbackAcknowledgmentEmail(finalEmail, finalName, session.programName, {
Expand Down
Loading
Loading