61 lines
1.8 KiB
JavaScript
61 lines
1.8 KiB
JavaScript
import { AnnouncemntModal } from "./announcementModal.js";
|
|
|
|
export const createAnnouncemnet = async (req, res) => {
|
|
const { sentTo, message } = req.body;
|
|
|
|
if (!sentTo || !message) {
|
|
return res.status(400).send("Send to and message are required");
|
|
}
|
|
|
|
try {
|
|
const newAnnouncement = new AnnouncemntModal({ sentTo, message });
|
|
await newAnnouncement.save();
|
|
res.status(201).json({ message: "Announcement created" });
|
|
} catch (err) {
|
|
console.log(err);
|
|
res.status(500).json({ error: "Server error" });
|
|
}
|
|
};
|
|
|
|
export const getAnnouncements = async (req, res) => {
|
|
const { page = 1, rowsPerPage = 5 } = req.query;
|
|
|
|
try {
|
|
// Calculate pagination parameters
|
|
const skip = (page - 1) * rowsPerPage;
|
|
const limit = parseInt(rowsPerPage, 10);
|
|
|
|
// Get total count of announcements
|
|
const totalAnnouncements = await AnnouncemntModal.countDocuments();
|
|
|
|
// Fetch announcements with pagination
|
|
const announcements = await AnnouncemntModal.find()
|
|
.skip(skip)
|
|
.limit(limit)
|
|
.sort({ createdAt: -1 }); // Sort by timestamp (most recent first)
|
|
|
|
res.status(200).json({
|
|
announcements,
|
|
totalAnnouncements,
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({ message: "Error fetching announcements", error });
|
|
}
|
|
};
|
|
|
|
// Get announcements for a specific role (RDs, PDs, SCs, or TMs)
|
|
// Controller to get announcements for a specific role
|
|
export const getAnnouncementsByRole = async (req, res) => {
|
|
try {
|
|
// Extract role from the URL path, e.g., 'RDs', 'PDs', etc.
|
|
const role = req.path.split("/").pop();
|
|
console.log("role");
|
|
|
|
const announcements = await AnnouncemntModal.find({ sentTo: role });
|
|
res.status(200).json(announcements);
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.status(500).json({ error: "Server error" });
|
|
}
|
|
};
|