Skip to content
Open
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
8 changes: 1 addition & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

149 changes: 149 additions & 0 deletions src/controllers/pmeducatorsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
const mongoose = require('mongoose');
const Educator = require('../models/pmEducators');
const Student = require('../models/pmStudents');

const toInt = (v, def, min = 1, max = 1000) => {
const n = Number.parseInt(v, 10);
if (Number.isNaN(n)) return def;
return Math.min(Math.max(n, min), max);
};

const shapeEducatorList = (e) => ({
id: String(e._id),
name: e.name,
subject: e.subject,
studentCount: e.studentCount ?? 0,
});

const getEducators = async (req, res) => {
try {
const data = await Educator.find().lean();

// If DB is empty → return mock data
if (!data.length) {
return res.json({
data: [
{ id: 't-001', name: 'Alice Johnson', subject: 'Mathematics', studentCount: 3 },
{ id: 't-002', name: 'Brian Lee', subject: 'Science', studentCount: 2 },
{ id: 't-003', name: 'John Doe', subject: 'English', studentCount: 1 },
],
mock: true,
});
}

res.json({
data: data.map((e) => ({
id: String(e._id),
name: e.name,
subject: e.subject,
studentCount: e.studentCount ?? 0,
})),
});
} catch (err) {
console.error('getEducators error:', err);
res.status(500).json({ error: 'Failed to fetch educators' });
}
};

const getEducatorById = async (req, res) => {
try {
const { educatorId } = req.params;
if (!mongoose.isValidObjectId(educatorId))
return res.status(400).json({ error: 'Invalid educatorId' });
const edu = await Educator.findById(educatorId);
if (!edu) return res.status(404).json({ error: 'Educator not found' });
res.json({
data: shapeEducatorList({
...edu.toObject(),
studentCount: await Student.countDocuments({ educator: edu._id }),
}),
});
} catch (err) {
console.error('getEducatorById error:', err);
res.status(500).json({ error: 'Failed to fetch educator' });
}
};

const getStudentsByEducator = async (req, res) => {
try {
const { educatorId } = req.params;

const hasAny = await Student.countDocuments();
if (!hasAny) {
const mockData = {
't-001': [
{ id: 's-101', name: 'Jay', grade: '7', progress: 0.78 },
{ id: 's-102', name: 'Kate', grade: '7', progress: 0.62 },
{ id: 's-103', name: 'Sam', grade: '8', progress: 0.85 },
],
't-002': [
{ id: 's-201', name: 'Alina Gupta', grade: '6', progress: 0.54 },
{ id: 's-202', name: 'Samir Khan', grade: '6', progress: 0.91 },
],
't-003': [{ id: 's-301', name: 'Ryan', grade: '7', progress: 0.73 }],
};
return res.json({ data: mockData[educatorId] || [] });
}

const data = await Student.find({ educator: educatorId }).lean();
res.json({ data });
} catch (err) {
console.error('getStudentsByEducator error:', err);
res.status(500).json({ error: 'Failed to fetch students' });
}
};

const getSubjects = async (_req, res) => {
try {
const subjects = await Educator.distinct('subject');
res.json({ data: subjects.sort(), total: subjects.length });
} catch (err) {
console.error('getSubjects error:', err);
res.status(500).json({ error: 'Failed to fetch subjects' });
}
};

const searchStudentsAcrossEducators = async (req, res) => {
try {
const q = String(req.query.q || '').trim();
const page = toInt(req.query.page, 1, 1, 9999);
const limit = toInt(req.query.limit, 10, 1, 100);

const match = {};
if (q) match.name = { $regex: q, $options: 'i' };

const total = await Student.countDocuments(match);
const totalPages = Math.max(1, Math.ceil(total / limit));
const currentPage = Math.min(Math.max(1, page), totalPages);

const data = await Student.find(match)
.populate({ path: 'educator', select: 'name subject' })
.sort({ name: 1 })
.skip((currentPage - 1) * limit)
.limit(limit)
.lean();

const shaped = data.map((s) => ({
id: String(s._id),
name: s.name,
grade: s.grade,
progress: s.progress,
educatorId: s.educator ? String(s.educator._id) : null,
educatorName: s.educator ? s.educator.name : null,
subject: s.educator ? s.educator.subject : null,
}));

res.json({ data: shaped, page: currentPage, totalPages, total, filters: { q } });
} catch (err) {
console.error('searchStudentsAcrossEducators error:', err);
res.status(500).json({ error: 'Failed to search students' });
}
};

module.exports = {
getEducators,
getEducatorById,
getStudentsByEducator,
getSubjects,
searchStudentsAcrossEducators,
};
130 changes: 130 additions & 0 deletions src/controllers/pmnotificationsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
const mongoose = require('mongoose');
const Educator = require('../models/pmEducators');
const PMNotification = require('../models/pmNotification');

const isObjId = (s) => /^[a-f0-9]{24}$/i.test(String(s || ''));
const sanitizeMessage = (msg) =>
String(msg || '')
.replace(/\s+/g, ' ')
.trim();

async function resolveRecipients(educatorIds = [], all = false) {
const raw = Array.isArray(educatorIds) ? educatorIds.map(String).filter(Boolean) : [];

const anyNonObjectId = raw.some((id) => !isObjId(id));
if (anyNonObjectId) {
return {
mode: 'mock',
attempted: raw.length || (all ? 1 : 0),
validIds: raw,
unknownIds: [],
};
}

// Real mode
const totalEducators = await Educator.estimatedDocumentCount();

if (all === true) {
if (totalEducators === 0) {
return { mode: 'real', attempted: 0, validIds: [], unknownIds: [] };
}
const ids = await Educator.find().distinct('_id');
return { mode: 'real', attempted: ids.length, validIds: ids.map(String), unknownIds: [] };
}

const asObjIds = raw.map((id) => new mongoose.Types.ObjectId(id));
const found = asObjIds.length
? await Educator.find({ _id: { $in: asObjIds } })
.select('_id')
.lean()
: [];
const foundSet = new Set(found.map((d) => String(d._id)));
const validIds = raw.filter((id) => foundSet.has(id));
const unknownIds = raw.filter((id) => !foundSet.has(id));

return { mode: 'real', attempted: raw.length, validIds, unknownIds };
}

async function previewNotification(req, res) {
try {
const { educatorIds, all, message } = req.body || {};
const msg = sanitizeMessage(message);
if (!msg) return res.status(400).json({ error: 'message is required' });
if (msg.length > 1000)
return res.status(400).json({ error: 'message must be ≤ 1000 characters' });

const { mode, attempted, validIds, unknownIds } = await resolveRecipients(educatorIds, all);
if (attempted === 0 && all !== true) {
return res.status(400).json({ error: 'Provide at least one educatorId or set all=true' });
}

return res.json({
ok: true,
mode,
summary: { attempted, willSendTo: validIds.length, unknownIds, all: !!all },
message: msg,
});
} catch (err) {
console.error('previewNotification error:', err);
res.status(500).json({ error: 'Failed to preview notification' });
}
}

async function sendNotification(req, res) {
try {
const { educatorIds, all, message } = req.body || {};
const msg = sanitizeMessage(message);
if (!msg) return res.status(400).json({ error: 'message is required' });
if (msg.length > 1000)
return res.status(400).json({ error: 'message must be ≤ 1000 characters' });

const { mode, attempted, validIds, unknownIds } = await resolveRecipients(educatorIds, all);
if (attempted === 0 && all !== true) {
return res.status(400).json({ error: 'Provide at least one educatorId or set all=true' });
}

if (mode === 'mock') {
return res.status(201).json({
ok: true,
mode: 'mock',
notification: {
id: null,
message: msg,
educatorIds: validIds,
createdAt: new Date().toISOString(),
},
summary: { attempted, sentTo: validIds.length, unknownIds, all: !!all },
});
}

if (validIds.length === 0) {
return res.status(400).json({ error: 'No valid educatorIds provided', unknownIds });
}

const doc = await PMNotification.create({
message: msg,
educatorIds: validIds.map((id) => new mongoose.Types.ObjectId(id)),
createdBy: req.user?._id || undefined,
});

return res.status(201).json({
ok: true,
mode: 'real',
notification: {
id: String(doc._id),
message: doc.message,
educatorIds: doc.educatorIds.map(String),
createdAt: doc.createdAt.toISOString(),
},
summary: { attempted, sentTo: validIds.length, unknownIds, all: !!all },
});
} catch (err) {
console.error('sendNotification error:', err);
res.status(500).json({ error: 'Failed to send notification' });
}
}

module.exports = {
previewNotification,
sendNotification,
};
13 changes: 13 additions & 0 deletions src/models/pmEducators.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const mongoose = require("mongoose");

const EducatorSchema = new mongoose.Schema(
{
externalId: { type: String, index: true, unique: true, sparse: true },

name: { type: String, required: true, index: true },
subject: { type: String, required: true, index: true },
},
{ timestamps: true }
);

module.exports = mongoose.model("Educator", EducatorSchema);
12 changes: 12 additions & 0 deletions src/models/pmNotification.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const mongoose = require("mongoose");

const PMNotificationSchema = new mongoose.Schema(
{
message: { type: String, required: true, maxlength: 1000 },
educatorIds: [{ type: mongoose.Schema.Types.ObjectId, ref: "Educator", index: true }],
createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "UserProfile" },
},
{ timestamps: true }
);

module.exports = mongoose.model("PMNotification", PMNotificationSchema);
13 changes: 13 additions & 0 deletions src/models/pmStudents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const mongoose = require("mongoose");

const StudentSchema = new mongoose.Schema(
{
name: { type: String, required: true, index: true },
grade: { type: String, required: true },
progress: { type: Number, default: 0 },
educator: { type: mongoose.Schema.Types.ObjectId, ref: "Educator", required: true, index: true },
},
{ timestamps: true }
);

module.exports = mongoose.model("Student", StudentSchema);
Loading
Loading