UNPKG

ajinkya-mhetre-mern

Version:

A MERN starter with frontend and backend folders

241 lines (205 loc) 6.15 kB
// ===== src/controllers/farmerController.js ===== const Product = require('../models/Product'); const Order = require('../models/Order'); const cloudinary = require('../config/cloudinary'); const fs = require('fs'); const addProduct = async (req, res) => { try { const { name, description, category, price, unit, availableQuantity, harvestDate, expiryDate } = req.body; const productData = { name, description, category, price: parseFloat(price), unit, availableQuantity: parseInt(availableQuantity), farmer: req.user._id, harvestDate: harvestDate ? new Date(harvestDate) : undefined, expiryDate: expiryDate ? new Date(expiryDate) : undefined }; // Handle image uploads if (req.files && req.files.length > 0) { const imageUploadPromises = req.files.map(async (file) => { const result = await cloudinary.uploader.upload(file.path, { folder: 'farm-products', transformation: [ { width: 800, height: 600, crop: 'fill' } ] }); // Delete local file after upload fs.unlinkSync(file.path); return { url: result.secure_url, public_id: result.public_id }; }); productData.images = await Promise.all(imageUploadPromises); } const product = await Product.create(productData); await product.populate('farmer', 'name email'); res.status(201).json({ success: true, message: 'Product added successfully', product }); } catch (error) { // Clean up uploaded files if error occurs console.log('Error adding product:', error); if (req.files) { req.files.forEach(file => { if (fs.existsSync(file.path)) { fs.unlinkSync(file.path); } }); } res.status(500).json({ message: error }); } }; const getMyProducts = async (req, res) => { try { const products = await Product.find({ farmer: req.user._id }) .populate('farmer', 'name email') .sort({ createdAt: -1 }); res.json({ success: true, products }); } catch (error) { res.status(500).json({ message: error.message }); } }; const updateProduct = async (req, res) => { try { const { productId } = req.params; const updates = req.body; const product = await Product.findOne({ _id: productId, farmer: req.user._id }); if (!product) { return res.status(404).json({ message: 'Product not found' }); } Object.keys(updates).forEach(key => { if (updates[key] !== undefined) { product[key] = updates[key]; } }); await product.save(); await product.populate('farmer', 'name email'); res.json({ success: true, message: 'Product updated successfully', product }); } catch (error) { res.status(500).json({ message: error.message }); } }; const deleteProduct = async (req, res) => { try { const { productId } = req.params; const product = await Product.findOne({ _id: productId, farmer: req.user._id }); if (!product) { return res.status(404).json({ message: 'Product not found' }); } // Delete images from cloudinary if (product.images && product.images.length > 0) { const deletePromises = product.images.map(image => cloudinary.uploader.destroy(image.public_id) ); await Promise.all(deletePromises); } await Product.findByIdAndDelete(productId); res.json({ success: true, message: 'Product deleted successfully' }); } catch (error) { res.status(500).json({ message: error.message }); } }; const getMyOrders = async (req, res) => { try { const orders = await Order.find({ 'items.farmer': req.user._id }) .populate('customer', 'name email phone') .populate('items.product', 'name images') .sort({ createdAt: -1 }); res.json({ success: true, orders }); } catch (error) { res.status(500).json({ message: error.message }); } }; const updateOrderStatus = async (req, res) => { try { const { orderId } = req.params; const { status, note } = req.body; const order = await Order.findOne({ _id: orderId, 'items.farmer': req.user._id }); if (!order) { return res.status(404).json({ message: 'Order not found' }); } order.status = status; order.statusHistory.push({ status, note: note || `Order ${status}`, timestamp: new Date() }); await order.save(); // Emit real-time update const io = req.app.get('socketio'); io.to(order.customer.toString()).emit('orderStatusUpdate', { orderId: order._id, status: order.status, timestamp: new Date() }); res.json({ success: true, message: 'Order status updated successfully', order }); } catch (error) { res.status(500).json({ message: error.message }); } }; const getDashboardStats = async (req, res) => { try { const totalProducts = await Product.countDocuments({ farmer: req.user._id }); const activeProducts = await Product.countDocuments({ farmer: req.user._id, isActive: true }); const totalOrders = await Order.countDocuments({ 'items.farmer': req.user._id }); const pendingOrders = await Order.countDocuments({ 'items.farmer': req.user._id, status: { $in: ['placed', 'processing'] } }); res.json({ success: true, stats: { totalProducts, activeProducts, totalOrders, pendingOrders } }); } catch (error) { res.status(500).json({ message: error.message }); } }; module.exports = { addProduct, getMyProducts, updateProduct, deleteProduct, getMyOrders, updateOrderStatus, getDashboardStats };