import VisitRDandPD from './VisitRD&PDModel.js'; const parseDate = (dateStr) => { const [day, month, year] = dateStr.split("/").map(Number); // Create a UTC date object to ensure the correct date is stored return new Date(Date.UTC(year, month - 1, day)); }; // Controller for creating a visit record export const createVisit = async (req, res) => { try { const visitBy = req.user._id; const visitUserType = req.userType; const { addedFor, addedForId, tradename, visitDate, note } = req.body; if (!addedFor || !addedForId || !tradename || !visitDate) { return res.status(400).json({ message: 'All fields are required' }); } const parsedDate = parseDate(visitDate); // Create a new visit record const newVisit = new VisitRDandPD({ visitBy, visitUserType, addedFor, addedForId, tradename, visitDate: parsedDate, note, }); // Save the visit record to the database const savedVisit = await newVisit.save(); return res.status(201).json({ message: 'Visit done successfully', visit: savedVisit }); } catch (error) { console.error(error); return res.status(500).json({ message: 'Server error' }); } }; // Controller for fetching all visits for a specific distributor (RD or PD) export const getVisitsByDistributor = async (req, res) => { try { const { distributorId, distributorType } = req.params; // Validate distributor type if (!['RetailDistributor', 'PrincipalDistributor'].includes(distributorType)) { return res.status(400).json({ message: 'Invalid distributor type' }); } // Find all visits for the specified distributor const visits = await VisitRDandPD.find({ addedFor: distributorType, addedForId: distributorId, }).populate('visitBy', 'name email'); // Populating visitBy with user details if (!visits.length) { return res.status(404).json({ message: 'No visits found for this distributor' }); } return res.status(200).json({ visits }); } catch (error) { console.error(error); return res.status(500).json({ message: 'Server error' }); } };