| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212 |
- require('dotenv').config();
- const express = require('express');
- const cors = require('cors');
- const fs = require('fs');
- const path = require('path');
-
- const app = express();
- const PORT = process.env.PORT || 3002;
-
- app.use(cors());
- app.use(express.json());
-
- // 使用 JSON 文件存储数据 - 修复路径
- const dbPath = path.join(__dirname, '..', '..', 'data', 'crm-data.json');
-
- function loadDB() {
- try {
- if (fs.existsSync(dbPath)) {
- return JSON.parse(fs.readFileSync(dbPath, 'utf-8'));
- }
- } catch (e) {
- console.error('加载数据库失败:', e.message);
- }
- return { customers: [], followUps: [] };
- }
-
- function saveDB(data) {
- try {
- const dir = path.dirname(dbPath);
- if (!fs.existsSync(dir)) {
- fs.mkdirSync(dir, { recursive: true });
- }
- fs.writeFileSync(dbPath, JSON.stringify(data, null, 2), 'utf-8');
- console.log('💾 数据已保存:', dbPath);
- } catch (e) {
- console.error('保存数据库失败:', e.message);
- }
- }
-
- // 初始化
- let db = loadDB();
- console.log('📊 数据文件:', dbPath);
- console.log('📝 当前客户数:', db.customers.length);
-
- // 健康检查
- app.get('/api/health', (req, res) => {
- res.json({ status: 'ok', service: 'CRM API', customers: db.customers.length });
- });
-
- // 获取客户列表
- app.get('/api/customers', (req, res) => {
- try {
- const { status, keyword } = req.query;
- let customers = db.customers;
-
- if (status) {
- customers = customers.filter(c => c.status === status);
- }
- if (keyword) {
- const k = keyword.toLowerCase();
- customers = customers.filter(c =>
- c.name.toLowerCase().includes(k) ||
- (c.company && c.company.toLowerCase().includes(k)) ||
- (c.phone && c.phone.includes(k))
- );
- }
-
- customers.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
- 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.customers.find(c => c.id == req.params.id);
- if (!customer) {
- return res.status(404).json({ success: false, error: '客户不存在' });
- }
-
- const followUps = db.followUps.filter(f => f.customer_id == req.params.id)
- .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
-
- 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 customer = {
- id: Date.now(),
- name,
- company: company || '',
- phone: phone || '',
- email: email || '',
- source: source || '',
- status: 'potential',
- notes: notes || '',
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString()
- };
-
- db.customers.push(customer);
- saveDB(db);
-
- res.json({ success: true, data: { id: customer.id }, message: '客户创建成功' });
- } catch (error) {
- console.error('创建客户失败:', error);
- res.status(500).json({ success: false, error: error.message });
- }
- });
-
- // 更新客户
- app.put('/api/customers/:id', (req, res) => {
- try {
- const index = db.customers.findIndex(c => c.id == req.params.id);
- if (index === -1) {
- return res.status(404).json({ success: false, error: '客户不存在' });
- }
-
- const { name, company, phone, email, source, status, notes } = req.body;
- db.customers[index] = {
- ...db.customers[index],
- name, company, phone, email, source, status, notes,
- updated_at: new Date().toISOString()
- };
-
- saveDB(db);
- res.json({ success: true, message: '客户更新成功' });
- } catch (error) {
- res.status(500).json({ success: false, error: error.message });
- }
- });
-
- // 删除客户
- app.delete('/api/customers/:id', (req, res) => {
- try {
- const index = db.customers.findIndex(c => c.id == req.params.id);
- if (index === -1) {
- return res.status(404).json({ success: false, error: '客户不存在' });
- }
-
- db.customers.splice(index, 1);
- db.followUps = db.followUps.filter(f => f.customer_id != req.params.id);
- saveDB(db);
-
- 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 followUp = {
- id: Date.now(),
- customer_id: parseInt(req.params.id),
- type: type || '',
- content: content || '',
- next_followup: nextFollowup || null,
- created_at: new Date().toISOString()
- };
-
- db.followUps.push(followUp);
-
- // 更新客户状态
- if (type === '成交') {
- const index = db.customers.findIndex(c => c.id == req.params.id);
- if (index !== -1) {
- db.customers[index].status = 'customer';
- db.customers[index].updated_at = new Date().toISOString();
- }
- }
-
- saveDB(db);
- res.json({ success: true, data: { id: followUp.id }, message: '跟进记录添加成功' });
- } catch (error) {
- res.status(500).json({ success: false, error: error.message });
- }
- });
-
- // 获取统计数据
- app.get('/api/stats', (req, res) => {
- try {
- const total = db.customers.length;
- const potential = db.customers.filter(c => c.status === 'potential').length;
- const contacting = db.customers.filter(c => c.status === 'contacting').length;
- const customer = db.customers.filter(c => c.status === 'customer').length;
-
- 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}`);
- });
|