Spaces:
Sleeping
Sleeping
Update src/core/services/database_service.py
Browse files
src/core/services/database_service.py
CHANGED
|
@@ -2,12 +2,13 @@
|
|
| 2 |
import sqlite3
|
| 3 |
from contextlib import contextmanager
|
| 4 |
from pathlib import Path
|
| 5 |
-
from typing import Dict, List, Any, Optional
|
| 6 |
import json
|
| 7 |
from datetime import datetime, timedelta
|
| 8 |
import random
|
| 9 |
from faker import Faker
|
| 10 |
import uuid
|
|
|
|
| 11 |
import os
|
| 12 |
|
| 13 |
class DatabaseService:
|
|
@@ -338,4 +339,112 @@ class DatabaseService:
|
|
| 338 |
'contact_count': contact_count,
|
| 339 |
'interaction_count': interaction_stats['interaction_count'],
|
| 340 |
'avg_sentiment': interaction_stats['avg_sentiment'] or 0.0
|
| 341 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import sqlite3
|
| 3 |
from contextlib import contextmanager
|
| 4 |
from pathlib import Path
|
| 5 |
+
from typing import Dict, List, Any, Optional, Tuple
|
| 6 |
import json
|
| 7 |
from datetime import datetime, timedelta
|
| 8 |
import random
|
| 9 |
from faker import Faker
|
| 10 |
import uuid
|
| 11 |
+
import pandas as pd
|
| 12 |
import os
|
| 13 |
|
| 14 |
class DatabaseService:
|
|
|
|
| 339 |
'contact_count': contact_count,
|
| 340 |
'interaction_count': interaction_stats['interaction_count'],
|
| 341 |
'avg_sentiment': interaction_stats['avg_sentiment'] or 0.0
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
def get_recent_interactions(self, user_id: str = None, limit: int = 10) -> List[Dict]:
|
| 345 |
+
"""Get recent interactions with account and user details"""
|
| 346 |
+
with self.get_db() as conn:
|
| 347 |
+
query = """
|
| 348 |
+
SELECT
|
| 349 |
+
i.*,
|
| 350 |
+
a.name as account_name,
|
| 351 |
+
u.name as owner_name,
|
| 352 |
+
a.industry as account_industry
|
| 353 |
+
FROM interactions i
|
| 354 |
+
JOIN accounts a ON i.account_id = a.id
|
| 355 |
+
JOIN users u ON i.owner_id = u.id
|
| 356 |
+
"""
|
| 357 |
+
params = []
|
| 358 |
+
|
| 359 |
+
if user_id:
|
| 360 |
+
query += " WHERE i.owner_id = ?"
|
| 361 |
+
params.append(user_id)
|
| 362 |
+
|
| 363 |
+
query += " ORDER BY i.created_at DESC LIMIT ?"
|
| 364 |
+
params.append(limit)
|
| 365 |
+
|
| 366 |
+
cursor = conn.execute(query, params)
|
| 367 |
+
return [dict(row) for row in cursor.fetchall()]
|
| 368 |
+
|
| 369 |
+
def search_interactions(self, query: str, user_id: Optional[str] = None, limit: int = 10) -> List[Dict]:
|
| 370 |
+
"""Search interactions by content"""
|
| 371 |
+
with self.get_db() as conn:
|
| 372 |
+
sql_query = """
|
| 373 |
+
SELECT
|
| 374 |
+
i.*,
|
| 375 |
+
a.name as account_name,
|
| 376 |
+
u.name as owner_name
|
| 377 |
+
FROM interactions i
|
| 378 |
+
JOIN accounts a ON i.account_id = a.id
|
| 379 |
+
JOIN users u ON i.owner_id = u.id
|
| 380 |
+
WHERE (i.transcript LIKE ? OR i.summary LIKE ?)
|
| 381 |
+
"""
|
| 382 |
+
params = [f"%{query}%", f"%{query}%"]
|
| 383 |
+
|
| 384 |
+
if user_id:
|
| 385 |
+
sql_query += " AND i.owner_id = ?"
|
| 386 |
+
params.append(user_id)
|
| 387 |
+
|
| 388 |
+
sql_query += " ORDER BY i.created_at DESC LIMIT ?"
|
| 389 |
+
params.append(limit)
|
| 390 |
+
|
| 391 |
+
cursor = conn.execute(sql_query, params)
|
| 392 |
+
return [dict(row) for row in cursor.fetchall()]
|
| 393 |
+
|
| 394 |
+
def get_dashboard_data(self) -> Tuple[Dict, pd.DataFrame, pd.DataFrame]:
|
| 395 |
+
"""Get aggregated data for dashboard"""
|
| 396 |
+
with self.get_db() as conn:
|
| 397 |
+
# Get counts
|
| 398 |
+
counts = {
|
| 399 |
+
'accounts': conn.execute('SELECT COUNT(*) FROM accounts').fetchone()[0],
|
| 400 |
+
'contacts': conn.execute('SELECT COUNT(*) FROM contacts').fetchone()[0],
|
| 401 |
+
'interactions': conn.execute('SELECT COUNT(*) FROM interactions').fetchone()[0]
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
# Get recent interactions
|
| 405 |
+
recent_interactions = pd.read_sql("""
|
| 406 |
+
SELECT
|
| 407 |
+
i.created_at, i.type,
|
| 408 |
+
a.name as account_name,
|
| 409 |
+
u.name as owner_name,
|
| 410 |
+
i.sentiment_score
|
| 411 |
+
FROM interactions i
|
| 412 |
+
JOIN accounts a ON i.account_id = a.id
|
| 413 |
+
JOIN users u ON i.owner_id = u.id
|
| 414 |
+
ORDER BY i.created_at DESC
|
| 415 |
+
LIMIT 10
|
| 416 |
+
""", conn)
|
| 417 |
+
|
| 418 |
+
# Get account distribution
|
| 419 |
+
account_distribution = pd.read_sql("""
|
| 420 |
+
SELECT industry, COUNT(*) as count
|
| 421 |
+
FROM accounts
|
| 422 |
+
GROUP BY industry
|
| 423 |
+
""", conn)
|
| 424 |
+
|
| 425 |
+
return counts, recent_interactions, account_distribution
|
| 426 |
+
|
| 427 |
+
def save_interaction(self, interaction_data: Dict[str, Any]) -> str:
|
| 428 |
+
"""Save a new interaction to the database"""
|
| 429 |
+
with self.get_db() as conn:
|
| 430 |
+
cursor = conn.cursor()
|
| 431 |
+
|
| 432 |
+
# Ensure required fields
|
| 433 |
+
required_fields = ['id', 'type', 'account_id', 'owner_id', 'created_at']
|
| 434 |
+
for field in required_fields:
|
| 435 |
+
if field not in interaction_data:
|
| 436 |
+
raise ValueError(f"Missing required field: {field}")
|
| 437 |
+
|
| 438 |
+
# Convert any dict/list fields to JSON
|
| 439 |
+
if 'metadata' in interaction_data and isinstance(interaction_data['metadata'], (dict, list)):
|
| 440 |
+
interaction_data['metadata'] = json.dumps(interaction_data['metadata'])
|
| 441 |
+
|
| 442 |
+
# Build query dynamically based on provided fields
|
| 443 |
+
fields = interaction_data.keys()
|
| 444 |
+
placeholders = ','.join(['?' for _ in fields])
|
| 445 |
+
query = f"INSERT INTO interactions ({','.join(fields)}) VALUES ({placeholders})"
|
| 446 |
+
|
| 447 |
+
cursor.execute(query, list(interaction_data.values()))
|
| 448 |
+
conn.commit()
|
| 449 |
+
|
| 450 |
+
return interaction_data['id']
|