Skip to content
Open
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
37 changes: 25 additions & 12 deletions app-backend/src/controllers/shift.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import Shift from '../models/Shift.js';
import Branch from '../models/Branch.js';
import Guard from '../models/Guard.js';
import Availability from '../models/Availability.js';
import ShiftAttendance from '../models/ShiftAttendance.js';

import { ACTIONS } from "../middleware/logger.js";

Expand Down Expand Up @@ -526,23 +525,37 @@ export const listAvailableShifts = async (req, res) => {
}

const findQ = Shift.find(query)
.sort({ date: role === 'guard' ? 1 : -1, startTime: role === 'guard' ? 1 : -1, createdAt: -1 })
.skip(skip).limit(limit)
.populate('createdBy', 'name');
.sort({
date: role === 'guard' ? 1 : -1,
startTime: role === 'guard' ? 1 : -1,
createdAt: -1,
})
.skip(skip)
.limit(limit)
.populate('createdBy', 'name email')
.populate('guardIds', 'name email')
.populate('acceptedBy', 'name email');

if (role === 'employer' || role === 'admin') {
findQ.populate('applicants', 'name email');
}

const [docs, total] = await Promise.all([findQ.lean(), Shift.countDocuments(query)]);

const items = (role === 'employer' || role === 'admin')
? docs.map(d => ({
...d,
applicantCount: Array.isArray(d.applicants) ? d.applicants.length : 0,
hasApplicants: Array.isArray(d.applicants) && d.applicants.length > 0,
}))
: docs;
const items = docs.map((shift) => {
const assignedGuards = shift.acceptedBy
? [shift.acceptedBy]
: Array.isArray(shift.guardIds)
? shift.guardIds
: [];

return {
...shift,
assignedGuards,
applicantCount: Array.isArray(shift.applicants) ? shift.applicants.length : 0,
hasApplicants: Array.isArray(shift.applicants) && shift.applicants.length > 0,
};
});

res.json({ page, limit, total, items });
} catch (e) {
Expand All @@ -566,7 +579,7 @@ export const applyForShift = async (req, res) => {
const shift = await Shift.findById(id);
if (!shift) return res.status(404).json({ message: 'Shift not found' });
if (shift.status !== 'open') {
return res.status(400).json({ message: 'Can only apply to open shifts' });
return res.status(400).json({ message: 'Can only apply to open shifts' });
}

if (['assigned', 'completed'].includes(shift.status)) {
Expand Down
Loading