Skip to content
Merged
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
66 changes: 35 additions & 31 deletions backend/src/controllers/meeting/getUserMeetings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,25 @@ export async function getUserMeetings(req: AuthRequest, res: Response, next: Nex
const currentUserTeamId = req.user.teamId?.toString();
const targetUserId = req.params.userId;

// Everyone can view their own meetings
if (currentUserId === targetUserId) {
// Determine the user's role to fetch appropriate meetings
if (currentUserRole === UserRole.INTERVIEWER) {
const meetings = await Meeting.find({ interviewerIds: targetUserId });
return ApiResponseUtil.success(res, meetings, 'Meetings retrieved successfully');
} else {
// Candidates and admins
const meetings = await Meeting.find({
$or: [
{ candidateId: targetUserId },
{ interviewerIds: targetUserId }
]
});
return ApiResponseUtil.success(res, meetings, 'Meetings retrieved successfully');
}
}
// Everyone can view their own meetings
if (currentUserId === targetUserId) {
// Determine the user's role to fetch appropriate meetings
if (currentUserRole === UserRole.INTERVIEWER) {
const meetings = await Meeting.find({ interviewerIds: targetUserId })
.populate('interviewerIds', 'name email');
return ApiResponseUtil.success(res, meetings, 'Meetings retrieved successfully');
} else {
// Candidates and admins
const meetings = await Meeting.find({
$or: [
{ candidateId: targetUserId },
{ interviewerIds: targetUserId }
]
})
.populate('interviewerIds', 'name email');
return ApiResponseUtil.success(res, meetings, 'Meetings retrieved successfully');
}
}

// For viewing others' meetings, check team-based permissions
const targetUser = await User.findById(targetUserId);
Expand All @@ -61,20 +63,22 @@ export async function getUserMeetings(req: AuthRequest, res: Response, next: Nex
return ApiResponseUtil.error(res, 'Access denied: you can only view meetings of team members', 403);
}

// Fetch meetings based on target user's role
const targetUserRole = targetUser.role || UserRole.CANDIDATE;
if (targetUserRole === UserRole.INTERVIEWER) {
const meetings = await Meeting.find({ interviewerIds: targetUserId });
return ApiResponseUtil.success(res, meetings, 'Meetings retrieved successfully');
} else {
const meetings = await Meeting.find({
$or: [
{ candidateId: targetUserId },
{ interviewerIds: targetUserId }
]
});
return ApiResponseUtil.success(res, meetings, 'Meetings retrieved successfully');
}
// Fetch meetings based on target user's role
const targetUserRole = targetUser.role || UserRole.CANDIDATE;
if (targetUserRole === UserRole.INTERVIEWER) {
const meetings = await Meeting.find({ interviewerIds: targetUserId })
.populate('interviewerIds', 'name email');
return ApiResponseUtil.success(res, meetings, 'Meetings retrieved successfully');
} else {
const meetings = await Meeting.find({
$or: [
{ candidateId: targetUserId },
{ interviewerIds: targetUserId }
]
})
.populate('interviewerIds', 'name email');
return ApiResponseUtil.success(res, meetings, 'Meetings retrieved successfully');
}
} catch (error) {
next(error);
}
Expand Down
88 changes: 2 additions & 86 deletions frontend/src/features/dashboard/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,86 +10,6 @@ import { AdminSettings } from "../admin/components";

export default function Dashboard() {
const [activePage, setActivePage] = useState<string>("dashboard");
const currentDate = new Date().getDate(); // get current date

// Function to extract day number from date string
const getDayFromDate = (dateString: string): number => {
const match = dateString.match(/(\d+)/);
return match ? parseInt(match[1]) : 0;
};

// list containing the upcoming interviews, uses the CalendarCard componenet to allow for dynamically added interviews
// add an object to this list an it will appear as a new interview
const interviews = [
{
id: 1,
role: "Frontend Developer",
interviewer: "Interviewer #2",
date: "Thursday, Oct 9, 2:00 PM",
},
{
id: 2,
role: "Backend Developer",
interviewer: "Interviewer #3",
date: " Thursday, Oct 9, 4:00 PM",
},
{
id: 3,
role: "Full Stack Developer",
interviewer: "Interviewer #1",
date: "Saturday, Oct 10, 3:30 PM",
},
{
id: 4,
role: "Full Stack Developer",
interviewer: "Interviewer #2",
date: "Monday, Oct 20, 3:30 PM",
},
{
id: 5,
role: "Full Stack Developer",
interviewer: "Interviewer #4",
date: "monday, Oct 11, 3:30 PM",
},
];

// TODO: create a system that will schedule interviews and connect it to this list

// Function to categorize interviews based on current date
const categorizeInterviews = (interviewsList: typeof interviews) => {
// create a list with all interviews happening today
const todayInterviews = interviewsList.filter((interview) => {
const interviewDay = getDayFromDate(interview.date);
return interviewDay === currentDate;
});

// create a list with all interviews happening this week
const thisWeekInterviews = interviewsList.filter((interview) => {
const interviewDay = getDayFromDate(interview.date);
return interviewDay >= currentDate && interviewDay <= currentDate + 6;
});

// create a list with all interviews happening in the next 7 days
const next7DaysInterviews = interviewsList.filter((interview) => {
const interviewDay = getDayFromDate(interview.date);
return interviewDay >= currentDate && interviewDay <= currentDate + 7;
});

// return these three in a json format - will become stats
return {
today: todayInterviews.length,
thisWeek: thisWeekInterviews.length,
next7Days: next7DaysInterviews.length,
};
};

const stats = categorizeInterviews(interviews);

const calendarStats = [
{ title: "Today's Interviews", count: stats.today },
{ title: "This week's interviews", count: stats.thisWeek },
{ title: "Next 7 days", count: stats.next7Days },
];

return (
<div className="flex h-screen pt-20">
Expand All @@ -100,12 +20,8 @@ export default function Dashboard() {
<DashboardHeader />
{activePage === "dashboard" ? (
<>
<CalendarStats stats={calendarStats} />
<InterviewScheduleSection
interviews={interviews}
getDayFromDate={getDayFromDate}
currentDate={currentDate}
/>
<CalendarStats />
<InterviewScheduleSection />
</>
) : activePage === "admin-settings" ? (
<AdminSettings />
Expand Down
114 changes: 106 additions & 8 deletions frontend/src/features/dashboard/components/Availability.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import * as React from "react";
import { useState } from "react";
import { useState, useContext } from "react";
import { Check } from "lucide-react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { AuthContext } from "@/features/auth/services/AuthContext";
import { authenticatedFetch } from "@/features/auth/utils/authClient";
import { combineDateAndTime, toISOTimestamp } from "@/utils/timezone";

interface AvailabilityData {
[dateKey: string]: string[];
Expand All @@ -27,10 +30,16 @@ const MONTHS = ["January", "February", "March", "April", "May", "June", "July",
const TIME_SLOTS = ["8:00 am", "9:00 am", "10:00 am", "11:00 am", "12:00 pm", "1:00 pm", "2:00 pm", "3:00 pm", "4:00 pm", "5:00 pm", "6:00 pm", "7:00 pm", "8:00 pm", "9:00 pm", "10:00 pm", "11:00 pm"];

export default function Availability() {
const auth = useContext(AuthContext);
const user = auth?.user;

const [selectedDate, setSelectedDate] = useState<Date | null>(null);
const [availability, setAvailability] = useState<AvailabilityData>({});
const [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [currentYear, setCurrentYear] = useState(new Date().getFullYear());
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const [submitSuccess, setSubmitSuccess] = useState(false);

const formatDateKey = (date: Date): string => {
const year = date.getFullYear();
Expand Down Expand Up @@ -91,8 +100,72 @@ export default function Availability() {
};

const handleSubmit = async () => {
console.log("Submitting availability:", availability);
alert("Availability submitted successfully!");
// Check if user has a team
if (!user?.teamId) {
setSubmitError("You must join a team before submitting availability.");
return;
}

if (Object.keys(availability).length === 0) {
setSubmitError("Please select at least one time slot.");
return;
}

setIsSubmitting(true);
setSubmitError(null);
setSubmitSuccess(false);

try {
// Transform availability data to API format
const availabilitySlots: Array<{ teamId: string; startTime: string; endTime: string; type: string }> = [];

for (const [dateKey, timeSlots] of Object.entries(availability)) {
const date = new Date(dateKey);

for (const timeSlot of timeSlots) {
const startDateTime = combineDateAndTime(date, timeSlot);
// Each slot is 1 hour
const endDateTime = new Date(startDateTime);
endDateTime.setHours(endDateTime.getHours() + 1);

availabilitySlots.push({
teamId: user.teamId,
startTime: toISOTimestamp(startDateTime),
endTime: toISOTimestamp(endDateTime),
type: "available",
});
}
}

// Submit each availability slot
await Promise.all(
availabilitySlots.map(async (slot) => {
const response = await authenticatedFetch("/availability", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(slot),
});

if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: "Failed to submit availability" }));
throw new Error(errorData.message || `Failed to submit slot at ${slot.startTime}`);
}

return response.json();
})
);

setSubmitSuccess(true);
// Clear availability after successful submission
setAvailability({});
setSelectedDate(null);
} catch (err) {
setSubmitError(err instanceof Error ? err.message : "Failed to submit availability. Please try again.");
} finally {
setIsSubmitting(false);
}
};

const days = generateCalendarDays();
Expand Down Expand Up @@ -156,10 +229,35 @@ export default function Availability() {
</div>
)}

<button onClick={handleSubmit} disabled={Object.keys(availability).length === 0} className="w-full bg-black text-white py-3 px-6 rounded-lg font-medium hover:bg-gray-800 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed">
Submit Availability
</button>
</div>
);
{!user?.teamId && (
<div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
<p className="text-yellow-800">
<strong>Cannot submit availability:</strong> You must join a team first.
Please contact your moderator or check your email for a team invitation.
</p>
</div>
)}

{submitError && (
<div className="p-4 bg-red-50 border border-red-200 rounded-lg">
<p className="text-red-700">{submitError}</p>
</div>
)}

{submitSuccess && (
<div className="p-4 bg-green-50 border border-green-200 rounded-lg">
<p className="text-green-700">Availability submitted successfully!</p>
</div>
)}

<button
onClick={handleSubmit}
disabled={Object.keys(availability).length === 0 || isSubmitting || !user?.teamId}
className="w-full bg-black text-white py-3 px-6 rounded-lg font-medium hover:bg-gray-800 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed"
>
{isSubmitting ? "Submitting..." : "Submit Availability"}
</button>
</div>
);
}

Loading