ehsan-dashboards/dashboards/crm/api_server.py

135 lines
4.9 KiB
Python
Executable file

import http.server
import socketserver
import json
import os
import sqlite3
from datetime import datetime
PORT = 8096
DATA_FILE = '/data/dashboards/ekeepa/crm/leads.json'
DB_FILE = '/data/dashboards/ekeepa/crm/crm_audit.db'
def init_db():
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
lead_id TEXT,
timestamp TEXT,
action TEXT,
stage TEXT,
followup_count INTEGER,
note TEXT,
raw_payload TEXT
)
''')
conn.commit()
conn.close()
class CRMHandler(http.server.BaseHTTPRequestHandler):
def _send_headers(self, code=200, content_type='application/json; charset=utf-8'):
self.send_response(code)
self.send_header('Content-Type', content_type)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
self.end_headers()
def do_OPTIONS(self):
self._send_headers(200)
def do_GET(self):
path = self.path.split('?')[0]
if path in ['/', '/leads', '/api/leads']:
if not os.path.exists(DATA_FILE):
self._send_headers(404)
self.wfile.write(json.dumps({'error': 'Data file not found'}).encode('utf-8'))
return
try:
with open(DATA_FILE, 'r', encoding='utf-8') as f:
data = f.read()
self._send_headers(200)
self.wfile.write(data.encode('utf-8'))
except Exception as e:
self._send_headers(500)
self.wfile.write(json.dumps({'error': str(e)}).encode('utf-8'))
elif path in ['/health', '/ping']:
self._send_headers(200)
self.wfile.write(json.dumps({'status': 'ok', 'time': datetime.now().isoformat()}).encode('utf-8'))
else:
self._send_headers(404)
def do_POST(self):
path = self.path.split('?')[0]
if path in ['/update', '/api/update']:
content_len = int(self.headers.get('Content-Length', 0))
post_body = self.rfile.read(content_len)
try:
payload = json.loads(post_body.decode('utf-8'))
lead_id = payload.get('id')
if not lead_id:
self._send_headers(400)
self.wfile.write(b'{"error": "Missing lead id"}')
return
with open(DATA_FILE, 'r', encoding='utf-8') as f:
leads = json.load(f)
updated = False
for idx, item in enumerate(leads):
if item.get('id') == lead_id:
for k, v in payload.items():
item[k] = v
leads[idx] = item
updated = True
break
if not updated:
self._send_headers(404)
self.wfile.write(b'{"error": "Lead not found"}')
return
tmp_file = DATA_FILE + '.tmp'
with open(tmp_file, 'w', encoding='utf-8') as f:
json.dump(leads, f, ensure_ascii=False, indent=2)
os.replace(tmp_file, DATA_FILE)
try:
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
c.execute('''
INSERT INTO audit_log (lead_id, timestamp, action, stage, followup_count, note, raw_payload)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
lead_id,
datetime.now().isoformat(),
payload.get('last_action', 'update'),
payload.get('stage', ''),
payload.get('followup_count', 0),
payload.get('latest_note', ''),
json.dumps(payload, ensure_ascii=False)
))
conn.commit()
conn.close()
except Exception as db_err:
print(f"SQLite audit log error: {db_err}")
self._send_headers(200)
self.wfile.write(json.dumps({'success': True, 'lead_id': lead_id, 'updated_at': datetime.now().isoformat()}).encode('utf-8'))
except Exception as e:
self._send_headers(500)
self.wfile.write(json.dumps({'error': str(e)}).encode('utf-8'))
else:
self._send_headers(404)
if __name__ == '__main__':
init_db()
print(f"Starting CRM API Server on port {PORT}...")
with socketserver.TCPServer(('0.0.0.0', PORT), CRMHandler) as httpd:
httpd.serve_forever()