require('dotenv').config(); const express = require('express'); const cors = require('cors'); const Database = require('better-sqlite3'); const path = require('path'); const app = express(); const PORT = process.env.PORT || 3002; app.use(cors()); app.use(express.json()); // 初始化数据库 const dbPath = path.join(__dirname, '..', 'data', 'crm.db'); const db = new Database(dbPath); // 创建客户表 db.exec(` CREATE TABLE IF NOT EXISTS customers ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, company TEXT, phone TEXT, email TEXT, source TEXT, status TEXT DEFAULT 'potential', notes TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); // 创建跟进记录表 db.exec(` CREATE TABLE IF NOT EXISTS follow_ups ( id INTEGER PRIMARY KEY AUTOINCREMENT, customer_id INTEGER NOT NULL, type TEXT, content TEXT, next_followup DATE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE ) `); // 健康检查 app.get('/api/health', (req, res) => { res.json({ status: 'ok', service: 'CRM API' }); }); // 获取客户列表 app.get('/api/customers', (req, res) => { try { const { status, keyword } = req.query; let sql = 'SELECT * FROM customers WHERE 1=1'; const params = []; if (status) { sql += ' AND status = ?'; params.push(status); } if (keyword) { sql += ' AND (name LIKE ? OR company LIKE ? OR phone LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`, `%${keyword}%`); } sql += ' ORDER BY created_at DESC'; const customers = db.prepare(sql).all(...params); res.json({ success: true, data: customers }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); // 获取客户详情 app.get('/api/customers/:id', (req, res) => { try { const customer = db.prepare('SELECT * FROM customers WHERE id = ?').get(req.params.id); if (!customer) { return res.status(404).json({ success: false, error: '客户不存在' }); } const followUps = db.prepare('SELECT * FROM follow_ups WHERE customer_id = ? ORDER BY created_at DESC') .all(req.params.id); res.json({ success: true, data: { ...customer, followUps } }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); // 创建客户 app.post('/api/customers', (req, res) => { try { const { name, company, phone, email, source, notes } = req.body; if (!name) { return res.status(400).json({ success: false, error: '客户名称必填' }); } const stmt = db.prepare(` INSERT INTO customers (name, company, phone, email, source, notes) VALUES (?, ?, ?, ?, ?, ?) `); const result = stmt.run(name, company || '', phone || '', email || '', source || '', notes || ''); res.json({ success: true, data: { id: result.lastInsertRowid }, message: '客户创建成功' }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); // 更新客户 app.put('/api/customers/:id', (req, res) => { try { const { name, company, phone, email, source, status, notes } = req.body; const stmt = db.prepare(` UPDATE customers SET name = ?, company = ?, phone = ?, email = ?, source = ?, status = ?, notes = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? `); stmt.run(name, company, phone, email, source, status, notes, req.params.id); res.json({ success: true, message: '客户更新成功' }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); // 删除客户 app.delete('/api/customers/:id', (req, res) => { try { db.prepare('DELETE FROM customers WHERE id = ?').run(req.params.id); res.json({ success: true, message: '客户删除成功' }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); // 添加跟进记录 app.post('/api/customers/:id/followups', (req, res) => { try { const { type, content, nextFollowup } = req.body; const stmt = db.prepare(` INSERT INTO follow_ups (customer_id, type, content, next_followup) VALUES (?, ?, ?, ?) `); const result = stmt.run(req.params.id, type || '', content || '', nextFollowup || null); // 更新客户状态 if (type === '成交') { db.prepare("UPDATE customers SET status = 'customer' WHERE id = ?").run(req.params.id); } res.json({ success: true, data: { id: result.lastInsertRowid }, message: '跟进记录添加成功' }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); // 获取统计数据 app.get('/api/stats', (req, res) => { try { const total = db.prepare('SELECT COUNT(*) as count FROM customers').get().count; const potential = db.prepare("SELECT COUNT(*) as count FROM customers WHERE status = 'potential'").get().count; const contacting = db.prepare("SELECT COUNT(*) as count FROM customers WHERE status = 'contacting'").get().count; const customer = db.prepare("SELECT COUNT(*) as count FROM customers WHERE status = 'customer'").get().count; res.json({ success: true, data: { total, potential, contacting, customer } }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); app.listen(PORT, () => { console.log(`🚀 CRM API 服务已启动:http://localhost:${PORT}`); console.log(`📊 数据库:${dbPath}`); });