const express = require('express'); const fs = require('fs'); const path = require('path'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const app = express(); const PORT = process.env.PORT || 3000; const JWT_SECRET = process.env.JWT_SECRET || 'bazar-keshavarzi-secret-2024'; const DB_PATH = path.join(__dirname, 'db.json'); app.use(express.json({ limit: '10mb' })); app.use(express.static(__dirname)); // ─── Database Helpers ──────────────────────────────────── function readDB() { try { return JSON.parse(fs.readFileSync(DB_PATH, 'utf-8')); } catch { return { users: [], products: [] }; } } function writeDB(data) { fs.writeFileSync(DB_PATH, JSON.stringify(data, null, 2), 'utf-8'); } // ─── Initialize Database ───────────────────────────────── async function initDB() { if (fs.existsSync(DB_PATH)) return; const users = [ { id: 1001, name: 'محمد رضایی', phone: '09121234567', email: 'm.rezaei@example.com', password: await bcrypt.hash('123456', 10), type: 'seller', createdAt: '2024-01-01T10:00:00Z' }, { id: 1002, name: 'زهرا احمدی', phone: '09129876543', email: 'z.ahmadi@example.com', password: await bcrypt.hash('123456', 10), type: 'seller', createdAt: '2024-01-05T08:30:00Z' }, { id: 1003, name: 'علی محمدی', phone: '09121112233', email: 'a.mohammadi@example.com', password: await bcrypt.hash('123456', 10), type: 'buyer', createdAt: '2024-01-10T12:00:00Z' }, ]; const products = [ { id: 2001, name: 'سیب قرمز', category: 'میوه‌ها', description: '۱۰۰ کیلوگرم سیب قرمز محلی، کاملاً ارگانیک و تازه', price: 45000, quantity: 100, location: 'خرم‌آباد', image: 'http://static.photos/nature/320x240/1', sellerId: 1001, sellerName: 'محمد رضایی', sellerPhone: '09121234567', status: 'active', createdAt: '2024-01-15T10:00:00Z' }, { id: 2002, name: 'گوجه فرنگی', category: 'سبزیجات', description: '۵۰ کیلوگرم گوجه فرنگی تازه و درجه یک', price: 32000, quantity: 50, location: 'تهران', image: 'http://static.photos/nature/320x240/2', sellerId: 1002, sellerName: 'زهرا احمدی', sellerPhone: '09129876543', status: 'active', createdAt: '2024-01-16T09:00:00Z' }, { id: 2003, name: 'گندم نیمه‌آماده', category: 'غلات', description: '۲۰۰ کیلوگرم گندم نیمه‌آماده با کیفیت بالا', price: 28000, quantity: 200, location: 'اصفهان', image: 'http://static.photos/nature/320x240/3', sellerId: 1001, sellerName: 'محمد رضایی', sellerPhone: '09121234567', status: 'active', createdAt: '2024-01-17T11:00:00Z' }, { id: 2004, name: 'مرغ تخم‌گذار', category: 'دام و طیور', description: '۵۰ عدد مرغ تخم‌گذار سالم و پرتولید', price: 120000, quantity: 50, location: 'مشهد', image: 'http://static.photos/nature/320x240/13', sellerId: 1002, sellerName: 'زهرا احمدی', sellerPhone: '09129876543', status: 'active', createdAt: '2024-01-18T08:00:00Z' }, { id: 2005, name: 'هندوانه خوشمزه', category: 'میوه‌ها', description: '۲۰ عدد هندوانه رسیده و شیرین', price: 15000, quantity: 20, location: 'کرمان', image: 'http://static.photos/nature/320x240/14', sellerId: 1001, sellerName: 'محمد رضایی', sellerPhone: '09121234567', status: 'active', createdAt: '2024-01-19T10:00:00Z' }, { id: 2006, name: 'جو کشت بهاره', category: 'غلات', description: '۵۰۰ کیلوگرم جو کشت بهاره درجه یک', price: 22000, quantity: 500, location: 'آذربایجان شرقی', image: 'http://static.photos/nature/320x240/15', sellerId: 1001, sellerName: 'محمد رضایی', sellerPhone: '09121234567', status: 'active', createdAt: '2024-01-20T09:00:00Z' }, { id: 2007, name: 'پرتقال تازه', category: 'میوه‌ها', description: '۸۰ کیلوگرم پرتقال تازه مازندرانی', price: 38000, quantity: 80, location: 'مازندران', image: 'http://static.photos/nature/320x240/5', sellerId: 1002, sellerName: 'زهرا احمدی', sellerPhone: '09129876543', status: 'active', createdAt: '2024-01-21T07:00:00Z' }, { id: 2008, name: 'سیب‌زمینی', category: 'سبزیجات', description: '۱۵۰ کیلوگرم سیب‌زمینی سفید همدان', price: 18000, quantity: 150, location: 'همدان', image: 'http://static.photos/nature/320x240/6', sellerId: 1001, sellerName: 'محمد رضایی', sellerPhone: '09121234567', status: 'active', createdAt: '2024-01-22T11:00:00Z' }, ]; writeDB({ users, products }); console.log('✅ Database initialized with seed data'); } // ─── Auth Middleware ────────────────────────────────────── function authenticate(req, res, next) { const header = req.headers.authorization; if (!header) return res.status(401).json({ error: 'لطفاً وارد شوید' }); try { req.user = jwt.verify(header.split(' ')[1], JWT_SECRET); next(); } catch { res.status(401).json({ error: 'توکن نامعتبر است. لطفاً دوباره وارد شوید' }); } } function requireSeller(req, res, next) { if (req.user.type !== 'seller') return res.status(403).json({ error: 'فقط فروشندگان مجاز به این عمل هستند' }); next(); } // ─── Auth Routes ───────────────────────────────────────── app.post('/api/register', async (req, res) => { try { const { name, phone, email, password, type } = req.body; if (!name || !phone || !password || !type) return res.status(400).json({ error: 'لطفاً تمام فیلدهای الزامی را پر کنید' }); const db = readDB(); if (db.users.find(u => u.phone === phone)) return res.status(400).json({ error: 'این شماره موبایل قبلاً ثبت شده است' }); const hashed = await bcrypt.hash(password, 10); const user = { id: Date.now(), name, phone, email: email || '', password: hashed, type, createdAt: new Date().toISOString() }; db.users.push(user); writeDB(db); const token = jwt.sign({ id: user.id, type: user.type }, JWT_SECRET, { expiresIn: '7d' }); res.status(201).json({ token, user: { id: user.id, name: user.name, phone: user.phone, email: user.email, type: user.type } }); } catch (err) { res.status(500).json({ error: 'خطای سرور. لطفاً دوباره تلاش کنید' }); } }); app.post('/api/login', async (req, res) => { try { const { phone, password } = req.body; if (!phone || !password) return res.status(400).json({ error: 'لطفاً شماره موبایل و رمز عبور را وارد کنید' }); const db = readDB(); const user = db.users.find(u => u.phone === phone); if (!user) return res.status(400).json({ error: 'کاربری با این شماره یافت نشد' }); if (!(await bcrypt.compare(password, user.password))) return res.status(400).json({ error: 'رمز عبور اشتباه است' }); const token = jwt.sign({ id: user.id, type: user.type }, JWT_SECRET, { expiresIn: '7d' }); res.json({ token, user: { id: user.id, name: user.name, phone: user.phone, email: user.email, type: user.type } }); } catch (err) { res.status(500).json({ error: 'خطای سرور. لطفاً دوباره تلاش کنید' }); } }); app.get('/api/me', authenticate, (req, res) => { const db = readDB(); const user = db.users.find(u => u.id === req.user.id); if (!user) return res.status(404).json({ error: 'کاربر یافت نشد' }); res.json({ id: user.id, name: user.name, phone: user.phone, email: user.email, type: user.type }); }); // ─── Product Routes ────────────────────────────────────── app.get('/api/products', (req, res) => { const db = readDB(); let products = db.products.filter(p => p.status === 'active'); const { category, location, search, minPrice, maxPrice } = req.query; if (category) products = products.filter(p => p.category === category); if (location) products = products.filter(p => p.location === location); if (search) { const s = search.toLowerCase(); products = products.filter(p => p.name.includes(s) || (p.description && p.description.includes(s))); } if (minPrice) products = products.filter(p => p.price >= Number(minPrice)); if (maxPrice) products = products.filter(p => p.price <= Number(maxPrice)); res.json(products); }); app.get('/api/products/:id', (req, res) => { const db = readDB(); const product = db.products.find(p => p.id === Number(req.params.id)); if (!product) return res.status(404).json({ error: 'محصول یافت نشد' }); res.json(product); }); app.post('/api/products', authenticate, requireSeller, (req, res) => { try { const { name, category, description, price, quantity, location, image } = req.body; if (!name || !category || !price || !location) return res.status(400).json({ error: 'لطفاً فیلدهای الزامی را پر کنید' }); const db = readDB(); const user = db.users.find(u => u.id === req.user.id); const product = { id: Date.now(), name, category, description: description || '', price: Number(price), quantity: Number(quantity) || 0, location, image: image || `http://static.photos/nature/320x240/${Math.floor(Math.random() * 999)}`, sellerId: req.user.id, sellerName: user.name, sellerPhone: user.phone, status: 'active', createdAt: new Date().toISOString() }; db.products.push(product); writeDB(db); res.status(201).json(product); } catch (err) { res.status(500).json({ error: 'خطای سرور' }); } }); app.put('/api/products/:id', authenticate, requireSeller, (req, res) => { try { const db = readDB(); const idx = db.products.findIndex(p => p.id === Number(req.params.id)); if (idx === -1) return res.status(404).json({ error: 'محصول یافت نشد' }); if (db.products[idx].sellerId !== req.user.id) return res.status(403).json({ error: 'شما مجاز به ویرایش این محصول نیستید' }); const allowed = ['name', 'category', 'description', 'price', 'quantity', 'location', 'image', 'status']; allowed.forEach(f => { if (req.body[f] !== undefined) db.products[idx][f] = req.body[f]; }); if (req.body.price) db.products[idx].price = Number(req.body.price); if (req.body.quantity) db.products[idx].quantity = Number(req.body.quantity); writeDB(db); res.json(db.products[idx]); } catch (err) { res.status(500).json({ error: 'خطای سرور' }); } }); app.delete('/api/products/:id', authenticate, requireSeller, (req, res) => { try { const db = readDB(); const idx = db.products.findIndex(p => p.id === Number(req.params.id)); if (idx === -1) return res.status(404).json({ error: 'محصول یافت نشد' }); if (db.products[idx].sellerId !== req.user.id) return res.status(403).json({ error: 'شما مجاز به حذف این محصول نیستید' }); db.products.splice(idx, 1); writeDB(db); res.json({ success: true, message: 'محصول با موفقیت حذف شد' }); } catch (err) { res.status(500).json({ error: 'خطای سرور' }); } }); app.get('/api/my-products', authenticate, (req, res) => { const db = readDB(); res.json(db.products.filter(p => p.sellerId === req.user.id)); }); // ─── Start Server ──────────────────────────────────────── initDB().then(() => { app.listen(PORT, () => { console.log(`🌿 بازار کشاورزی server running at http://localhost:${PORT}`); console.log(` Login with: 09121234567 / 123456 (seller) or 09121112233 / 123456 (buyer)`); }); });