UNPKG

ajinkya-mhetre-mern

Version:

A MERN starter with frontend and backend folders

823 lines (790 loc) 29 kB
// ===== seeds/seedData.js ===== const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const dotenv = require('dotenv'); const User = require('../src/models/User'); const Product = require('../src/models/Product'); const Order = require('../src/models/Order'); const connectDB = require('../src/config/database'); dotenv.config(); // Sample image URLs (you can replace with actual Cloudinary URLs) const sampleImages = { fruits: [ { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750148227/farm-products/xogt3qypxiyp8cpmhoz6.jpg', public_id: 'farm-products/xogt3qypxiyp8cpmhoz6' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-5.jpg', public_id: 'cld-sample-5' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-4.jpg', public_id: 'cld-sample-4' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-3.jpg', public_id: 'cld-sample-3' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-2.jpg', public_id: 'cld-sample-2' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-2.jpg', public_id: 'cld-sample-2' }, ], vegetables: [ { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750148227/farm-products/xogt3qypxiyp8cpmhoz6.jpg', public_id: 'farm-products/xogt3qypxiyp8cpmhoz6' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-4.jpg', public_id: 'cld-sample-4' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-4.jpg', public_id: 'cld-sample-4' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-3.jpg', public_id: 'cld-sample-3' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-2.jpg', public_id: 'cld-sample-2' }, { url: 'https://res.cloudinary.com/dpjymq0vc/image/upload/v1750147101/cld-sample-1.jpg', public_id: 'cld-sample-1' }, ] }; const seedData = async () => { try { // Connect to database await connectDB(); // Clear existing data console.log('Clearing existing data...'); await User.deleteMany({}); await Product.deleteMany({}); await Order.deleteMany({}); console.log('Creating seed data...'); // ===== USERS DATA ===== // Hash password function const hashPassword = async (password) => { return await bcrypt.hash(password, 12); }; // Admin Users const adminUsers = [ { name: 'Super Admin', email: 'admin@farmfresh.com', password: await hashPassword('admin123'), phone: '+91-9876543210', role: 'admin', isVerified: true, address: { street: '123 Admin Street', city: 'Mumbai', state: 'Maharashtra', zipCode: '400001' } }, { name: 'Assistant Admin', email: 'admin2@farmfresh.com', password: await hashPassword('admin123'), phone: '+91-9876543211', role: 'admin', isVerified: true, address: { street: '456 Management Road', city: 'Pune', state: 'Maharashtra', zipCode: '411001' } } ]; // Farmer Users const farmerUsers = [ { name: 'Rajesh Kumar', email: 'rajesh@farmer.com', password: await hashPassword('farmer123'), phone: '+91-9876543212', role: 'farmer', isVerified: true, address: { street: 'Village Khetpura', city: 'Nashik', state: 'Maharashtra', zipCode: '422001' }, farmDetails: { farmName: 'Kumar Organic Farm', farmSize: '5 acres', farmLocation: 'Nashik, Maharashtra', certifications: ['Organic Certified', 'APEDA Certified'] } }, { name: 'Priya Sharma', email: 'priya@farmer.com', password: await hashPassword('farmer123'), phone: '+91-9876543213', role: 'farmer', isVerified: true, address: { street: 'Village Greenfield', city: 'Satara', state: 'Maharashtra', zipCode: '415001' }, farmDetails: { farmName: 'Sharma Fresh Produce', farmSize: '8 acres', farmLocation: 'Satara, Maharashtra', certifications: ['ISO 22000', 'HACCP'] } }, { name: 'Amit Patel', email: 'amit@farmer.com', password: await hashPassword('farmer123'), phone: '+91-9876543214', role: 'farmer', isVerified: true, address: { street: 'Village Hariyali', city: 'Sangli', state: 'Maharashtra', zipCode: '416001' }, farmDetails: { farmName: 'Patel Fruit Gardens', farmSize: '12 acres', farmLocation: 'Sangli, Maharashtra', certifications: ['Organic Certified', 'Fair Trade'] } }, { name: 'Sunita Desai', email: 'sunita@farmer.com', password: await hashPassword('farmer123'), phone: '+91-9876543215', role: 'farmer', isVerified: true, address: { street: 'Village Subhash Nagar', city: 'Kolhapur', state: 'Maharashtra', zipCode: '416002' }, farmDetails: { farmName: 'Desai Vegetable Farm', farmSize: '6 acres', farmLocation: 'Kolhapur, Maharashtra', certifications: ['Organic Certified'] } }, { name: 'Vikram Singh', email: 'vikram@farmer.com', password: await hashPassword('farmer123'), phone: '+91-9876543216', role: 'farmer', isVerified: true, address: { street: 'Village Kisaan Nagar', city: 'Aurangabad', state: 'Maharashtra', zipCode: '431001' }, farmDetails: { farmName: 'Singh Agro Farm', farmSize: '15 acres', farmLocation: 'Aurangabad, Maharashtra', certifications: ['APEDA Certified', 'FSSAI Licensed'] } }, // Pending farmers (not verified) { name: 'Ramesh Yadav', email: 'ramesh@farmer.com', password: await hashPassword('farmer123'), phone: '+91-9876543217', role: 'farmer', isVerified: false, address: { street: 'Village New Hope', city: 'Solapur', state: 'Maharashtra', zipCode: '413001' }, farmDetails: { farmName: 'Yadav Fresh Farm', farmSize: '4 acres', farmLocation: 'Solapur, Maharashtra', certifications: [] } }, { name: 'Geeta Patil', email: 'geeta@farmer.com', password: await hashPassword('farmer123'), phone: '+91-9876543218', role: 'farmer', isVerified: false, address: { street: 'Village Green Valley', city: 'Ahmednagar', state: 'Maharashtra', zipCode: '414001' }, farmDetails: { farmName: 'Patil Organic Gardens', farmSize: '7 acres', farmLocation: 'Ahmednagar, Maharashtra', certifications: ['Pending Organic Certification'] } } ]; // Customer Users const customerUsers = [ { name: 'Anil Mehta', email: 'anil@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543219', role: 'customer', isVerified: true, address: { street: '101 Residential Complex', city: 'Mumbai', state: 'Maharashtra', zipCode: '400070' } }, { name: 'Neha Gupta', email: 'neha@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543220', role: 'customer', isVerified: true, address: { street: '202 Green Heights', city: 'Pune', state: 'Maharashtra', zipCode: '411038' } }, { name: 'Rohit Joshi', email: 'rohit@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543221', role: 'customer', isVerified: true, address: { street: '303 Sunrise Apartments', city: 'Navi Mumbai', state: 'Maharashtra', zipCode: '400614' } }, { name: 'Kavita Reddy', email: 'kavita@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543222', role: 'customer', isVerified: true, address: { street: '404 Lotus Gardens', city: 'Thane', state: 'Maharashtra', zipCode: '400601' } }, { name: 'Sanjay Tiwari', email: 'sanjay@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543223', role: 'customer', isVerified: true, address: { street: '505 Royal Residency', city: 'Nagpur', state: 'Maharashtra', zipCode: '440001' } }, { name: 'Deepika Shah', email: 'deepika@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543224', role: 'customer', isVerified: true, address: { street: '606 Paradise Heights', city: 'Kalyan', state: 'Maharashtra', zipCode: '421301' } }, { name: 'Manoj Kumar', email: 'manoj@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543225', role: 'customer', isVerified: true, address: { street: '707 Silver Oak', city: 'Nashik', state: 'Maharashtra', zipCode: '422005' } }, { name: 'Pooja Agarwal', email: 'pooja@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543226', role: 'customer', isVerified: true, address: { street: '808 Golden Heights', city: 'Aurangabad', state: 'Maharashtra', zipCode: '431005' } }, { name: 'Rahul Malhotra', email: 'rahul@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543227', role: 'customer', isVerified: true, address: { street: '909 Crystal Palace', city: 'Solapur', state: 'Maharashtra', zipCode: '413005' } }, { name: 'Anjali Verma', email: 'anjali@customer.com', password: await hashPassword('customer123'), phone: '+91-9876543228', role: 'customer', isVerified: true, address: { street: '1010 Diamond Plaza', city: 'Kolhapur', state: 'Maharashtra', zipCode: '416008' } } ]; // Create all users const allUsers = [...adminUsers, ...farmerUsers, ...customerUsers]; const createdUsers = await User.insertMany(allUsers); console.log(`Created ${createdUsers.length} users`); // Get user IDs for reference const farmers = createdUsers.filter(user => user.role === 'farmer' && user.isVerified); const customers = createdUsers.filter(user => user.role === 'customer'); // ===== PRODUCTS DATA ===== const productsData = [ // Farmer 1 - Rajesh Kumar (Fruits specialist) { name: 'Organic Red Apples', description: 'Fresh, crisp red apples grown organically without pesticides. Sweet and juicy, perfect for snacking or cooking.', category: 'fruit', price: 180, unit: 'kg', availableQuantity: 500, images: [sampleImages.fruits[0]], farmer: farmers[0]._id, isActive: true, harvestDate: new Date('2024-12-01'), expiryDate: new Date('2026-01-15') }, { name: 'Fresh Oranges', description: 'Juicy Valencia oranges packed with Vitamin C. Ideal for fresh juice or eating.', category: 'fruit', price: 120, unit: 'kg', availableQuantity: 800, images: [sampleImages.fruits[1]], farmer: farmers[0]._id, isActive: true, harvestDate: new Date('2024-11-25'), expiryDate: new Date('2026-01-10') }, { name: 'Premium Bananas', description: 'Naturally ripened bananas, rich in potassium and energy. Great for breakfast and smoothies.', category: 'fruit', price: 60, unit: 'dozen', availableQuantity: 200, images: [sampleImages.fruits[2]], farmer: farmers[0]._id, isActive: true, harvestDate: new Date('2024-12-10'), expiryDate: new Date('2026-12-25') }, // Farmer 2 - Priya Sharma (Mixed produce) { name: 'Alphonso Mangoes', description: 'King of mangoes - Alphonso variety known for its sweet taste and rich aroma. Limited season availability.', category: 'fruit', price: 450, unit: 'kg', availableQuantity: 150, images: [sampleImages.fruits[3]], farmer: farmers[1]._id, isActive: true, harvestDate: new Date('2024-12-05'), expiryDate: new Date('2026-12-20') }, { name: 'Organic Tomatoes', description: 'Vine-ripened organic tomatoes. Perfect for salads, cooking, and making fresh sauces.', category: 'vegetable', price: 80, unit: 'kg', availableQuantity: 600, images: [sampleImages.vegetables[0]], farmer: farmers[1]._id, isActive: true, harvestDate: new Date('2024-12-08'), expiryDate: new Date('2026-12-22') }, { name: 'Fresh Carrots', description: 'Crunchy orange carrots rich in beta-carotene. Great for salads, cooking, and juicing.', category: 'vegetable', price: 50, unit: 'kg', availableQuantity: 400, images: [sampleImages.vegetables[1]], farmer: farmers[1]._id, isActive: true, harvestDate: new Date('2024-12-06'), expiryDate: new Date('2026-01-05') }, // Farmer 3 - Amit Patel (Fruit specialist) { name: 'Black Grapes', description: 'Sweet and seedless black grapes. Rich in antioxidants and perfect for snacking.', category: 'fruit', price: 150, unit: 'kg', availableQuantity: 300, images: [sampleImages.fruits[4]], farmer: farmers[2]._id, isActive: true, harvestDate: new Date('2024-12-03'), expiryDate: new Date('2026-12-18') }, { name: 'Fresh Strawberries', description: 'Plump, red strawberries bursting with flavor. Perfect for desserts, smoothies, and direct consumption.', category: 'fruit', price: 320, unit: 'kg', availableQuantity: 100, images: [sampleImages.fruits[5]], farmer: farmers[2]._id, isActive: true, harvestDate: new Date('2024-12-12'), expiryDate: new Date('2026-12-19') }, // Farmer 4 - Sunita Desai (Vegetable specialist) { name: 'Farm Fresh Potatoes', description: 'High-quality potatoes perfect for all cooking needs. Freshly harvested from organic farms.', category: 'vegetable', price: 35, unit: 'kg', availableQuantity: 1000, images: [sampleImages.vegetables[2]], farmer: farmers[3]._id, isActive: true, harvestDate: new Date('2024-11-30'), expiryDate: new Date('2026-02-28') }, { name: 'Red Onions', description: 'Fresh red onions with strong flavor. Essential ingredient for Indian cooking.', category: 'vegetable', price: 45, unit: 'kg', availableQuantity: 800, images: [sampleImages.vegetables[3]], farmer: farmers[3]._id, isActive: true, harvestDate: new Date('2024-12-01'), expiryDate: new Date('2026-03-01') }, { name: 'Green Capsicum', description: 'Fresh green bell peppers. Crunchy and nutritious, perfect for stir-fries and salads.', category: 'vegetable', price: 70, unit: 'kg', availableQuantity: 250, images: [sampleImages.vegetables[4]], farmer: farmers[3]._id, isActive: true, harvestDate: new Date('2024-12-09'), expiryDate: new Date('2026-12-23') }, // Farmer 5 - Vikram Singh (Large scale mixed farming) { name: 'Organic Spinach', description: 'Fresh organic spinach leaves. Rich in iron and vitamins. Perfect for healthy meals.', category: 'vegetable', price: 40, unit: 'kg', availableQuantity: 200, images: [sampleImages.vegetables[5]], farmer: farmers[4]._id, isActive: true, harvestDate: new Date('2024-12-11'), expiryDate: new Date('2026-12-18') }, { name: 'Mixed Fruit Box', description: 'Assorted seasonal fruits box containing apples, oranges, and bananas. Perfect for families.', category: 'fruit', price: 300, unit: 'piece', availableQuantity: 50, images: [sampleImages.fruits[0], sampleImages.fruits[1]], farmer: farmers[4]._id, isActive: true, harvestDate: new Date('2024-12-10'), expiryDate: new Date('2026-12-24') }, // Some inactive/out of stock products { name: 'Seasonal Lemons', description: 'Fresh lemons for cooking and beverages.', category: 'fruit', price: 90, unit: 'kg', availableQuantity: 0, // Out of stock images: [sampleImages.fruits[1]], farmer: farmers[0]._id, isActive: false, harvestDate: new Date('2024-11-20'), expiryDate: new Date('2026-12-15') } ]; const createdProducts = await Product.insertMany(productsData); console.log(`Created ${createdProducts.length} products`); // ===== ORDERS DATA ===== // Helper function to create order items const createOrderItems = (products, quantities) => { return products.map((product, index) => ({ product: product._id, quantity: quantities[index], price: product.price, farmer: product.farmer })); }; // Helper function to calculate total amount const calculateTotal = (items) => { return items.reduce((total, item) => total + (item.price * item.quantity), 0); }; const ordersData = [ // Completed Orders { customer: customers[0]._id, // Anil Mehta items: createOrderItems([createdProducts[0], createdProducts[1]], [2, 3]), totalAmount: calculateTotal(createOrderItems([createdProducts[0], createdProducts[1]], [2, 3])), status: 'delivered', shippingAddress: { street: '101 Residential Complex', city: 'Mumbai', state: 'Maharashtra', zipCode: '400070' }, paymentStatus: 'paid', trackingNumber: 'FP1234567890', statusHistory: [ { status: 'placed', timestamp: new Date('2024-12-05T10:00:00Z'), note: 'Order placed successfully' }, { status: 'processing', timestamp: new Date('2024-12-05T12:00:00Z'), note: 'Order being prepared' }, { status: 'dispatched', timestamp: new Date('2024-12-06T09:00:00Z'), note: 'Order dispatched' }, { status: 'delivered', timestamp: new Date('2024-12-07T14:00:00Z'), note: 'Order delivered successfully' } ], createdAt: new Date('2024-12-05T10:00:00Z') }, { customer: customers[1]._id, // Neha Gupta items: createOrderItems([createdProducts[3], createdProducts[4]], [1, 2]), totalAmount: calculateTotal(createOrderItems([createdProducts[3], createdProducts[4]], [1, 2])), status: 'delivered', shippingAddress: { street: '202 Green Heights', city: 'Pune', state: 'Maharashtra', zipCode: '411038' }, paymentStatus: 'paid', trackingNumber: 'FP1234567891', statusHistory: [ { status: 'placed', timestamp: new Date('2024-12-03T15:30:00Z'), note: 'Order placed successfully' }, { status: 'processing', timestamp: new Date('2024-12-04T10:00:00Z'), note: 'Order confirmed by farmer' }, { status: 'dispatched', timestamp: new Date('2024-12-04T16:00:00Z'), note: 'Order out for delivery' }, { status: 'delivered', timestamp: new Date('2024-12-05T11:00:00Z'), note: 'Delivered to customer' } ], createdAt: new Date('2024-12-03T15:30:00Z') }, // Processing Orders { customer: customers[2]._id, // Rohit Joshi items: createOrderItems([createdProducts[6], createdProducts[7]], [2, 1]), totalAmount: calculateTotal(createOrderItems([createdProducts[6], createdProducts[7]], [2, 1])), status: 'processing', shippingAddress: { street: '303 Sunrise Apartments', city: 'Navi Mumbai', state: 'Maharashtra', zipCode: '400614' }, paymentStatus: 'paid', trackingNumber: 'FP1234567892', statusHistory: [ { status: 'placed', timestamp: new Date('2024-12-10T09:00:00Z'), note: 'Order placed successfully' }, { status: 'processing', timestamp: new Date('2024-12-10T11:00:00Z'), note: 'Order being prepared by farmer' } ], createdAt: new Date('2024-12-10T09:00:00Z') }, { customer: customers[3]._id, // Kavita Reddy items: createOrderItems([createdProducts[8], createdProducts[9], createdProducts[10]], [3, 2, 1]), totalAmount: calculateTotal(createOrderItems([createdProducts[8], createdProducts[9], createdProducts[10]], [3, 2, 1])), status: 'processing', shippingAddress: { street: '404 Lotus Gardens', city: 'Thane', state: 'Maharashtra', zipCode: '400601' }, paymentStatus: 'paid', trackingNumber: 'FP1234567893', statusHistory: [ { status: 'placed', timestamp: new Date('2024-12-11T14:00:00Z'), note: 'Large order placed' }, { status: 'processing', timestamp: new Date('2024-12-11T16:00:00Z'), note: 'Multiple farmers preparing items' } ], createdAt: new Date('2024-12-11T14:00:00Z') }, // Dispatched Orders { customer: customers[4]._id, // Sanjay Tiwari items: createOrderItems([createdProducts[2], createdProducts[5]], [5, 3]), totalAmount: calculateTotal(createOrderItems([createdProducts[2], createdProducts[5]], [5, 3])), status: 'dispatched', shippingAddress: { street: '505 Royal Residency', city: 'Nagpur', state: 'Maharashtra', zipCode: '440001' }, paymentStatus: 'paid', trackingNumber: 'FP1234567894', statusHistory: [ { status: 'placed', timestamp: new Date('2024-12-09T12:00:00Z'), note: 'Order placed successfully' }, { status: 'processing', timestamp: new Date('2024-12-09T14:00:00Z'), note: 'Order confirmed' }, { status: 'dispatched', timestamp: new Date('2024-12-10T08:00:00Z'), note: 'Order shipped to Nagpur' } ], createdAt: new Date('2024-12-09T12:00:00Z') }, // Placed Orders (Recent) { customer: customers[5]._id, // Deepika Shah items: createOrderItems([createdProducts[11]], [2]), totalAmount: calculateTotal(createOrderItems([createdProducts[11]], [2])), status: 'placed', shippingAddress: { street: '606 Paradise Heights', city: 'Kalyan', state: 'Maharashtra', zipCode: '421301' }, paymentStatus: 'paid', statusHistory: [ { status: 'placed', timestamp: new Date('2024-12-12T10:30:00Z'), note: 'Order placed successfully' } ], createdAt: new Date('2024-12-12T10:30:00Z') }, { customer: customers[6]._id, // Manoj Kumar items: createOrderItems([createdProducts[0], createdProducts[3], createdProducts[8]], [1, 2, 4]), totalAmount: calculateTotal(createOrderItems([createdProducts[0], createdProducts[3], createdProducts[8]], [1, 2, 4])), status: 'placed', shippingAddress: { street: '707 Silver Oak', city: 'Nashik', state: 'Maharashtra', zipCode: '422005' }, paymentStatus: 'pending', statusHistory: [ { status: 'placed', timestamp: new Date('2024-12-12T16:45:00Z'), note: 'Order placed, payment pending' } ], createdAt: new Date('2024-12-12T16:45:00Z') }, // Cancelled Orders { customer: customers[7]._id, // Pooja Agarwal items: createOrderItems([createdProducts[1], createdProducts[4]], [1, 1]), totalAmount: calculateTotal(createOrderItems([createdProducts[1], createdProducts[4]], [1, 1])), status: 'cancelled', shippingAddress: { street: '808 Golden Heights', city: 'Aurangabad', state: 'Maharashtra', zipCode: '431005' }, paymentStatus: 'failed', statusHistory: [ { status: 'placed', timestamp: new Date('2024-12-13T09:00:00Z'), note: 'Order placed successfully' }, { status: 'cancelled', timestamp: new Date('2024-12-13T11:00:00Z'), note: 'Order cancelled by customer' } ], createdAt: new Date('2024-12-13T09:00:00Z') }, { customer: customers[8]._id, // Rahul Malhotra items: createOrderItems([createdProducts[5], createdProducts[6]], [2, 1]), totalAmount: calculateTotal(createOrderItems([createdProducts[5], createdProducts[6]], [2, 1])), status: 'cancelled', shippingAddress: { street: '909 Crystal Palace', city: 'Solapur', state: 'Maharashtra', zipCode: '413005' }, paymentStatus: 'failed', statusHistory: [ { status: 'placed', timestamp: new Date('2024-12-13T10:30:00Z'), note: 'Order placed successfully' }, { status: 'cancelled', timestamp: new Date('2024-12-13T12:00:00Z'), note: 'Order cancelled by farmer due to stock unavailability' } ], createdAt: new Date('2024-12-13T10:30:00Z') } ]; const createdOrders = await Order.insertMany(ordersData); console.log(`Created ${createdOrders.length} orders`); console.log('Seeding completed successfully!'); } catch (error) { console.error('Error during seeding:', error); } finally { // Close the database connection await mongoose.connection.close(); } } // Run the seed function seedData() .then(() => console.log('Database seeded successfully!')) .catch(err => console.error('Error seeding database:', err)); // }); // { status: 'delivered', timestamp: new Date('2024-12-12T10:00:00Z'), note: 'Order delivered to customer' } // ] // }); // } catch (error) { // res.status(500).json({ message: error.message }); // } // } // // res.json({ // success: true, // order // }); // } catch (error) { // res.status(500).json({ message: error.message }); // } // }; // } catch (error) { // res.status(500).json({ message: error.message }); // } // } //