-
Notifications
You must be signed in to change notification settings - Fork 0
/
crm.py
1474 lines (1301 loc) · 64.5 KB
/
crm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sqlite3
import datetime
from typing import List, Dict, Optional, Any, Generator, TypeVar, ParamSpec, Callable, Tuple
import streamlit as st
import pandas as pd
import plotly.express as px
import requests
import json
import logging
import time
import queue
import threading
import re
import phonenumbers
from contextlib import contextmanager
from dataclasses import dataclass
from functools import wraps
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
import traceback
# Configure logging with RotatingFileHandler to prevent log files from growing indefinitely
from logging.handlers import RotatingFileHandler
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = RotatingFileHandler('crm_app.log', maxBytes=5*1024*1024, backupCount=5)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# Type hints for decorator
P = ParamSpec('P')
R = TypeVar('R')
# Custom Exceptions with additional attributes
class CRMException(Exception):
"""Base exception class for CRM errors"""
def __init__(self, message: str, error_code: Optional[int] = None, context: Optional[Dict[str, Any]] = None):
super().__init__(message)
self.error_code = error_code
self.context = context or {}
class DatabaseError(CRMException):
"""Database related errors"""
pass
class APIError(CRMException):
"""API related errors"""
pass
class ValidationError(CRMException):
"""Data validation errors"""
pass
def with_retry(
max_attempts: int = 3,
base_wait: float = 1,
max_wait: float = 10
) -> Callable[[Callable[P, R]], Callable[P, R]]:
"""
Decorator for retrying operations with exponential backoff
Args:
max_attempts: Maximum number of retry attempts
base_wait: Initial wait time between retries
max_wait: Maximum wait time between retries
"""
def decorator(func: Callable[P, R]) -> Callable[P, R]:
@retry(
stop=stop_after_attempt(max_attempts),
wait=wait_exponential(multiplier=base_wait, max=max_wait),
retry=retry_if_exception_type((requests.RequestException, DatabaseError, APIError)),
before_sleep=lambda retry_state: logger.warning(
f"Attempt {retry_state.attempt_number} failed: {retry_state.outcome.exception()}"
)
)
@wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
try:
return func(*args, **kwargs)
except Exception as e:
if isinstance(e, (requests.RequestException, DatabaseError, APIError)):
raise
logger.error(f"Unhandled error in {func.__name__}: {str(e)}", exc_info=True)
raise CRMException(f"Operation failed: {str(e)}")
return wrapper
return decorator
class DatabaseConnectionPool:
def __init__(self, db_name: str, max_connections: int = 5):
self.db_name = db_name
self.max_connections = max_connections
self.connections: queue.Queue = queue.Queue(maxsize=max_connections)
self.connection_count = 0
self._lock = threading.Lock()
def _create_connection(self) -> sqlite3.Connection:
"""Create a new database connection with pragmas for better performance"""
conn = sqlite3.connect(
self.db_name,
detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES
)
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
conn.execute("PRAGMA synchronous = NORMAL")
logger.info("Created new database connection")
return conn
@contextmanager
def get_connection(self) -> Generator[sqlite3.Connection, None, None]:
"""Get a database connection from the pool"""
connection = None
try:
try:
connection = self.connections.get_nowait()
logger.debug("Reusing existing database connection")
except queue.Empty:
with self._lock:
if self.connection_count < self.max_connections:
connection = self._create_connection()
self.connection_count += 1
else:
logger.debug("Waiting for available database connection")
connection = self.connections.get()
yield connection
except Exception as e:
logger.error(f"Database connection error: {str(e)}", exc_info=True)
if connection:
connection.close()
raise DatabaseError(f"Database connection failed: {str(e)}")
finally:
if connection:
try:
self.connections.put_nowait(connection)
except queue.Full:
connection.close()
with self._lock:
self.connection_count -= 1
logger.debug("Connection pool full. Closed excess connection.")
class Database:
def __init__(self, db_name: str = "crm.db"):
self.pool = DatabaseConnectionPool(db_name)
self.create_tables()
@contextmanager
def transaction(self) -> Generator[sqlite3.Connection, None, None]:
"""Context manager for database transactions"""
with self.pool.get_connection() as conn:
try:
yield conn
conn.commit()
except Exception as e:
conn.rollback()
logger.error(f"Transaction failed: {str(e)}", exc_info=True)
raise DatabaseError(f"Transaction failed: {str(e)}")
def execute(self, query: str, params: tuple = ()) -> Any:
"""Execute a database query"""
with self.transaction() as conn:
try:
cursor = conn.execute(query, params)
results = cursor.fetchall()
logger.debug(f"Executed query: {query} | Params: {params}")
return results
except sqlite3.Error as e:
logger.error(f"Query execution failed: {str(e)} | Query: {query} | Params: {params}", exc_info=True)
raise DatabaseError(f"Query execution failed: {str(e)}")
def execute_many(self, query: str, params_list: list[tuple]) -> None:
"""Execute multiple database queries"""
with self.transaction() as conn:
try:
conn.executemany(query, params_list)
logger.debug(f"Executed many queries: {query} | Number of params sets: {len(params_list)}")
except sqlite3.Error as e:
logger.error(f"Batch query execution failed: {str(e)} | Query: {query}", exc_info=True)
raise DatabaseError(f"Batch query execution failed: {str(e)}")
def create_tables(self):
"""Create all necessary database tables"""
tables = [
"""
CREATE TABLE IF NOT EXISTS company_info (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
city TEXT,
industry TEXT,
target_market TEXT,
unique_selling_points TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""",
"""
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
type TEXT CHECK(type IN ('Product', 'Service')),
description TEXT,
price REAL,
features TEXT,
target_audience TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""",
"""
CREATE TABLE IF NOT EXISTS clients (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT,
phone TEXT,
company TEXT,
industry TEXT,
notes TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""",
"""
CREATE TABLE IF NOT EXISTS deals (
id INTEGER PRIMARY KEY,
client_id INTEGER,
product_id INTEGER,
amount REAL,
status TEXT,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES clients (id),
FOREIGN KEY (product_id) REFERENCES products (id)
)
""",
"""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
due_date DATE,
status TEXT,
client_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES clients (id)
)
""",
"""
CREATE TABLE IF NOT EXISTS client_analyses (
id INTEGER PRIMARY KEY,
client_id INTEGER,
analysis TEXT,
generated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES clients (id)
)
""",
"""
CREATE TABLE IF NOT EXISTS deal_analyses (
id INTEGER PRIMARY KEY,
deal_id INTEGER,
analysis TEXT,
generated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (deal_id) REFERENCES deals (id)
)
"""
]
try:
with self.transaction() as conn:
for table in tables:
conn.execute(table)
logger.info("Database tables created successfully or already exist.")
except Exception as e:
logger.error(f"Error creating tables: {str(e)}", exc_info=True)
raise DatabaseError(f"Error creating tables: {str(e)}")
class InputValidator:
@staticmethod
def validate_email(email: str) -> bool:
"""Validate email format"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
@staticmethod
def validate_phone(phone: str, region: str = "US") -> bool:
"""Validate phone number format"""
try:
number = phonenumbers.parse(phone, region)
return phonenumbers.is_valid_number(number)
except phonenumbers.NumberParseException:
return False
@staticmethod
def validate_amount(amount: float) -> bool:
"""Validate monetary amount"""
return 0 <= amount <= 1e9 # Arbitrary upper limit
@staticmethod
def sanitize_text(text: str, max_length: int = 1000) -> str:
"""Sanitize text input"""
# Remove any potential SQL injection or XSS attempts
text = re.sub(r'[<>]', '', text)
text = text.replace("'", "''")
return text[:max_length]
@staticmethod
def validate_date(date_str: str) -> bool:
"""Validate date format (YYYY-MM-DD)"""
try:
datetime.datetime.strptime(date_str, '%Y-%m-%d')
return True
except ValueError:
return False
class DataValidator:
def validate_company_info(self, data: Dict[str, Any]) -> Dict[str, str]:
"""Validate company information"""
errors = {}
if not data.get('name'):
errors['name'] = "Company name is required"
elif len(data['name']) > 100:
errors['name'] = "Company name is too long"
if len(data.get('description', '')) > 1000:
errors['description'] = "Description is too long"
return errors
def validate_product(self, data: Dict[str, Any]) -> Dict[str, str]:
"""Validate product information"""
errors = {}
if not data.get('name'):
errors['name'] = "Product name is required"
if data.get('type') not in ['Product', 'Service']:
errors['type'] = "Invalid product type"
if not InputValidator.validate_amount(data.get('price', 0)):
errors['price'] = "Invalid price"
return errors
def validate_client(self, data: Dict[str, Any]) -> Dict[str, str]:
"""Validate client information"""
errors = {}
if not data.get('name'):
errors['name'] = "Client name is required"
if data.get('email') and not InputValidator.validate_email(data['email']):
errors['email'] = "Invalid email format"
if data.get('phone') and not InputValidator.validate_phone(data['phone']):
errors['phone'] = "Invalid phone number format"
return errors
def validate_deal(self, data: Dict[str, Any]) -> Dict[str, str]:
"""Validate deal information"""
errors = {}
if not data.get('client_id'):
errors['client_id'] = "Client is required"
if not data.get('product_id'):
errors['product_id'] = "Product is required"
if not InputValidator.validate_amount(data.get('amount', 0)):
errors['amount'] = "Invalid amount"
if data.get('status') not in ["New", "In Progress", "Won", "Lost", "On Hold"]:
errors['status'] = "Invalid deal status"
return errors
@dataclass
class RateLimitRule:
requests: int
period: int # in seconds
class InMemoryRateLimiter:
def __init__(self):
self._requests = {} # Dictionary to store request timestamps
self._lock = threading.Lock()
# Define rate limit rules
self.rules = {
'default': RateLimitRule(100, 3600), # 100 requests per hour
'ai_analysis': RateLimitRule(10, 60), # 10 AI analysis requests per minute
'database': RateLimitRule(1000, 3600), # 1000 database operations per hour
}
def _clean_old_requests(self, key: str, rule: RateLimitRule) -> None:
"""Remove requests older than the time window"""
current_time = time.time()
self._requests[key] = [
timestamp for timestamp in self._requests.get(key, [])
if current_time - timestamp < rule.period
]
def check_rate_limit(self, key: str, rule_name: str = 'default') -> Tuple[bool, Optional[float]]:
"""
Check if the request should be rate limited
Returns:
Tuple[bool, Optional[float]]: (is_allowed, retry_after)
"""
with self._lock:
rule = self.rules.get(rule_name, self.rules['default'])
if key not in self._requests:
self._requests[key] = []
self._clean_old_requests(key, rule)
if len(self._requests[key]) >= rule.requests:
oldest_timestamp = min(self._requests[key])
retry_after = rule.period - (time.time() - oldest_timestamp)
return False, max(0, retry_after)
self._requests[key].append(time.time())
return True, None
class RateLimitedAPI:
def __init__(self, ollama_url: str = "http://localhost:11434"):
self.rate_limiter = InMemoryRateLimiter()
self.ollama_url = ollama_url
@with_retry(max_attempts=3)
def make_ai_request(self, key: str, prompt: str) -> str:
"""Make an AI analysis request with rate limiting"""
is_allowed, retry_after = self.rate_limiter.check_rate_limit(key, 'ai_analysis')
if not is_allowed:
raise APIError(f"Rate limit exceeded. Try again in {retry_after:.1f} seconds")
try:
payload = {
"model": "gemma2:9b",
"prompt": prompt,
"stream": False
}
logger.debug(f"Sending AI request for {key} with payload: {json.dumps(payload)}")
response = requests.post(
f"{self.ollama_url}/api/generate",
json=payload,
timeout=30 # Increased timeout to 30 seconds
)
response.raise_for_status()
response_json = response.json()
logger.debug(f"AI Response for {key}: {response_json}")
return response_json.get('response', "No response from AI model.")
except requests.RequestException as e:
logger.error(f"AI request failed: {str(e)}", exc_info=True)
logger.error(f"Response Content: {response.text if 'response' in locals() else 'No response'}")
raise APIError(f"AI request failed: {str(e)}")
def serialize_for_json(obj: Any) -> Any:
"""Recursively convert datetime objects to ISO format strings."""
if isinstance(obj, dict):
return {k: serialize_for_json(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [serialize_for_json(item) for item in obj]
elif isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, datetime.date):
return obj.isoformat()
else:
return obj
class CRMAnalytics:
def __init__(self, ollama_url: str = "http://localhost:11434"):
self.api = RateLimitedAPI(ollama_url)
def analyze_client_potential(self, client_data: Dict, company_info: Dict, products: List[Dict]) -> str:
"""Analyze client potential using AI"""
# Serialize all data before sending
client_data_serialized = serialize_for_json(client_data)
company_info_serialized = serialize_for_json(company_info)
products_serialized = serialize_for_json(products)
prompt = f"""
Based on the following information, analyze the client's potential:
Company Context:
- Company: {company_info_serialized.get('name')}
- Industry: {company_info_serialized.get('industry')}
- City: {company_info_serialized.get('city')}
- Target Market: {company_info_serialized.get('target_market')}
- Unique Selling Points: {company_info_serialized.get('unique_selling_points')}
Client Information:
- Name: {client_data_serialized.get('name')}
- Industry: {client_data_serialized.get('industry')}
- Company: {client_data_serialized.get('company')}
- Notes: {client_data_serialized.get('notes')}
Available Products/Services:
{json.dumps(products_serialized, indent=2)}
Please provide a comprehensive analysis:
1. Client-Product Fit
2. Probability of successful deals
3. Recommended products/services for this client
4. Suggested approach and next actions
5. Potential deal value estimation
"""
return self.api.make_ai_request(f"client_analysis_{client_data_serialized.get('id')}", prompt)
def predict_deal_success(self, deal_data: Dict, client_data: Dict, product_data: Dict, company_info: Dict) -> str:
"""Predict deal success probability using AI"""
# Serialize all data before sending
deal_data_serialized = serialize_for_json(deal_data)
client_data_serialized = serialize_for_json(client_data)
product_data_serialized = serialize_for_json(product_data)
company_info_serialized = serialize_for_json(company_info)
prompt = f"""
Analyze the probability of successfully closing this deal based on the following context:
Company Information:
- Company: {company_info_serialized.get('name')}
- Industry: {company_info_serialized.get('industry')}
- City: {company_info_serialized.get('city')}
- Target Market: {company_info_serialized.get('target_market')}
- Unique Selling Points: {company_info_serialized.get('unique_selling_points')}
Client Information:
- Name: {client_data_serialized.get('name')}
- Industry: {client_data_serialized.get('industry')}
- Company: {client_data_serialized.get('company')}
Product/Service Information:
- Name: {product_data_serialized.get('name')}
- Type: {product_data_serialized.get('type')}
- Price: {product_data_serialized.get('price')}
- Target Audience: {product_data_serialized.get('target_audience')}
Deal Information:
- Amount: {deal_data_serialized.get('amount')}
- Description: {deal_data_serialized.get('description')}
Please provide:
1. Success probability percentage
2. Key risk factors
3. Competitive advantages
4. Recommended negotiation strategy
5. Value proposition alignment
6. Specific actions to increase success chances
"""
return self.api.make_ai_request(f"deal_analysis_{deal_data_serialized.get('id')}", prompt)
class CRM:
def __init__(self):
self.db = Database()
self.validator = DataValidator()
self.analytics = CRMAnalytics()
self.DEAL_STATUSES = ["New", "In Progress", "Won", "Lost", "On Hold"]
def save_company_info(self, data: Dict) -> bool:
"""Save company information"""
try:
# Validate input data
errors = self.validator.validate_company_info(data)
if errors:
raise ValidationError(str(errors))
# Sanitize text inputs
data = {k: InputValidator.sanitize_text(str(v)) if v else v
for k, v in data.items()}
with self.db.transaction() as conn:
# Check if company info exists
existing = conn.execute('SELECT id FROM company_info LIMIT 1').fetchone()
if existing:
# Update
conn.execute('''
UPDATE company_info
SET name=?, description=?, city=?, industry=?, target_market=?,
unique_selling_points=?, updated_at=CURRENT_TIMESTAMP
WHERE id=?
''', (
data['name'], data['description'], data['city'], data['industry'],
data['target_market'], data['unique_selling_points'], existing[0]
))
logger.info("Company information updated.")
else:
# Insert
conn.execute('''
INSERT INTO company_info
(name, description, city, industry, target_market, unique_selling_points)
VALUES (?, ?, ?, ?, ?, ?)
''', (
data['name'], data['description'], data['city'], data['industry'],
data['target_market'], data['unique_selling_points']
))
logger.info("Company information added.")
return True
except Exception as e:
logger.error(f"Error saving company information: {str(e)}", exc_info=True)
raise DatabaseError(f"Error saving company information: {str(e)}")
def get_company_info(self) -> Dict:
"""Get company information"""
try:
result = self.db.execute('''
SELECT name, description, city, industry, target_market, unique_selling_points
FROM company_info
LIMIT 1
''')
if result:
company_info = dict(zip(
['name', 'description', 'city', 'industry', 'target_market', 'unique_selling_points'],
result[0]
))
logger.info("Company information retrieved.")
return company_info
logger.info("No company information found.")
return {}
except Exception as e:
logger.error(f"Error retrieving company information: {str(e)}", exc_info=True)
raise DatabaseError(f"Error retrieving company information: {str(e)}")
def add_product(self, data: Dict) -> int:
"""Add a new product"""
try:
# Validate input data
errors = self.validator.validate_product(data)
if errors:
raise ValidationError(str(errors))
# Sanitize text inputs
data = {k: InputValidator.sanitize_text(str(v)) if v else v
for k, v in data.items()}
with self.db.transaction() as conn:
cursor = conn.execute('''
INSERT INTO products
(name, type, description, price, features, target_audience)
VALUES (?, ?, ?, ?, ?, ?)
''', (
data['name'], data['type'], data['description'],
data['price'], data['features'], data['target_audience']
))
product_id = cursor.lastrowid
logger.info(f"Product/Service added with ID: {product_id}.")
return product_id
except Exception as e:
logger.error(f"Error adding product/service: {str(e)}", exc_info=True)
raise DatabaseError(f"Error adding product/service: {str(e)}")
def get_products(self) -> List[Dict]:
"""Get all products"""
try:
results = self.db.execute('SELECT * FROM products')
columns = ['id', 'name', 'type', 'description', 'price', 'features', 'target_audience', 'created_at']
products = [dict(zip(columns, row)) for row in results]
logger.info(f"{len(products)} products/services retrieved.")
return products
except Exception as e:
logger.error(f"Error retrieving products/services: {str(e)}", exc_info=True)
raise DatabaseError(f"Error retrieving products/services: {str(e)}")
def get_product_by_id(self, product_id: int) -> Dict:
"""Get product by ID"""
try:
result = self.db.execute('SELECT * FROM products WHERE id = ?', (product_id,))
if not result:
logger.warning(f"Product with ID {product_id} not found.")
return {}
columns = ['id', 'name', 'type', 'description', 'price', 'features', 'target_audience', 'created_at']
product = dict(zip(columns, result[0]))
logger.info(f"Product retrieved by ID: {product_id}.")
return product
except Exception as e:
logger.error(f"Error retrieving product by ID {product_id}: {str(e)}", exc_info=True)
raise DatabaseError(f"Error retrieving product by ID {product_id}: {str(e)}")
def add_client(self, data: Dict) -> int:
"""Add a new client"""
try:
# Validate input data
errors = self.validator.validate_client(data)
if errors:
raise ValidationError(str(errors))
# Sanitize text inputs
data = {k: InputValidator.sanitize_text(str(v)) if v else v
for k, v in data.items()}
with self.db.transaction() as conn:
cursor = conn.execute('''
INSERT INTO clients
(name, email, phone, company, industry, notes)
VALUES (?, ?, ?, ?, ?, ?)
''', (
data['name'], data.get('email'), data.get('phone'),
data.get('company'), data.get('industry'), data.get('notes')
))
client_id = cursor.lastrowid
logger.info(f"Client added with ID: {client_id}.")
return client_id
except Exception as e:
logger.error(f"Error adding client: {str(e)}", exc_info=True)
raise DatabaseError(f"Error adding client: {str(e)}")
def get_client_by_id(self, client_id: int) -> Dict:
"""Get client by ID"""
try:
result = self.db.execute('SELECT * FROM clients WHERE id = ?', (client_id,))
if not result:
logger.warning(f"Client with ID {client_id} not found.")
return {}
columns = ['id', 'name', 'email', 'phone', 'company', 'industry', 'notes', 'created_at']
client = dict(zip(columns, result[0]))
logger.info(f"Client retrieved by ID: {client_id}.")
return client
except Exception as e:
logger.error(f"Error retrieving client by ID {client_id}: {str(e)}", exc_info=True)
raise DatabaseError(f"Error retrieving client by ID {client_id}: {str(e)}")
def save_client_analysis(self, client_id: int, analysis: str) -> bool:
"""Save client analysis"""
try:
with self.db.transaction() as conn:
conn.execute('''
INSERT INTO client_analyses (client_id, analysis)
VALUES (?, ?)
''', (client_id, InputValidator.sanitize_text(analysis)))
logger.info(f"Client analysis saved for ID {client_id}.")
return True
except Exception as e:
logger.error(f"Error saving client analysis: {str(e)}", exc_info=True)
raise DatabaseError(f"Error saving client analysis: {str(e)}")
def save_deal_analysis(self, deal_id: int, analysis: str) -> bool:
"""Save deal analysis"""
try:
with self.db.transaction() as conn:
conn.execute('''
INSERT INTO deal_analyses (deal_id, analysis)
VALUES (?, ?)
''', (deal_id, InputValidator.sanitize_text(analysis)))
logger.info(f"Deal analysis saved for ID {deal_id}.")
return True
except Exception as e:
logger.error(f"Error saving deal analysis: {str(e)}", exc_info=True)
raise DatabaseError(f"Error saving deal analysis: {str(e)}")
def get_client_analysis(self, client_id: int) -> Optional[Dict]:
"""Get latest client analysis"""
try:
result = self.db.execute('''
SELECT analysis, generated_at
FROM client_analyses
WHERE client_id = ?
ORDER BY generated_at DESC
LIMIT 1
''', (client_id,))
if result:
analysis = {
'analysis': result[0][0],
'generated_at': result[0][1]
}
logger.info(f"Client analysis retrieved for ID {client_id}.")
return analysis
logger.info(f"No client analysis found for ID {client_id}.")
return None
except Exception as e:
logger.error(f"Error retrieving client analysis: {str(e)}", exc_info=True)
raise DatabaseError(f"Error retrieving client analysis: {str(e)}")
def get_deal_analysis(self, deal_id: int) -> Optional[Dict]:
"""Get latest deal analysis"""
try:
result = self.db.execute('''
SELECT analysis, generated_at
FROM deal_analyses
WHERE deal_id = ?
ORDER BY generated_at DESC
LIMIT 1
''', (deal_id,))
if result:
analysis = {
'analysis': result[0][0],
'generated_at': result[0][1]
}
logger.info(f"Deal analysis retrieved for ID {deal_id}.")
return analysis
logger.info(f"No deal analysis found for ID {deal_id}.")
return None
except Exception as e:
logger.error(f"Error retrieving deal analysis: {str(e)}", exc_info=True)
raise DatabaseError(f"Error retrieving deal analysis: {str(e)}")
def regenerate_client_analysis(self, client_id: int) -> str:
"""Regenerate client analysis using AI"""
try:
client_data = self.get_client_by_id(client_id)
if not client_data:
raise ValidationError(f"Client with ID {client_id} not found")
company_info = self.get_company_info()
products = self.get_products()
logger.debug(f"Client Data: {client_data}")
logger.debug(f"Company Info: {company_info}")
logger.debug(f"Products: {products}")
analysis = self.analytics.analyze_client_potential(
client_data, company_info, products
)
logger.debug(f"AI Analysis Result: {analysis}")
self.save_client_analysis(client_id, analysis)
logger.info(f"Client analysis regenerated for ID {client_id}.")
return analysis
except APIError as e:
logger.error(f"APIError during client analysis regeneration: {str(e)}", exc_info=True)
raise
except Exception as e:
logger.error(f"Error regenerating client analysis: {str(e)}", exc_info=True)
raise APIError(f"Error regenerating client analysis: {str(e)}")
def regenerate_deal_analysis(self, deal_id: int) -> str:
"""Regenerate deal analysis using AI"""
try:
deal_result = self.db.execute('SELECT * FROM deals WHERE id = ?', (deal_id,))
if not deal_result:
raise ValidationError(f"Deal with ID {deal_id} not found")
columns = ['id', 'client_id', 'product_id', 'amount', 'status', 'description', 'created_at', 'updated_at']
deal_data = dict(zip(columns, deal_result[0]))
client_data = self.get_client_by_id(deal_data['client_id'])
product_data = self.get_product_by_id(deal_data['product_id'])
company_info = self.get_company_info()
analysis = self.analytics.predict_deal_success(
deal_data, client_data, product_data, company_info
)
self.save_deal_analysis(deal_id, analysis)
logger.info(f"Deal analysis regenerated for ID {deal_id}.")
return analysis
except APIError as e:
logger.error(f"APIError during deal analysis regeneration: {str(e)}", exc_info=True)
raise
except Exception as e:
logger.error(f"Error regenerating deal analysis: {str(e)}", exc_info=True)
raise APIError(f"Error regenerating deal analysis: {str(e)}")
def add_deal(self, data: Dict) -> int:
"""Add a new deal"""
try:
# Validate input data
errors = self.validator.validate_deal(data)
if errors:
raise ValidationError(str(errors))
# Sanitize text inputs
data = {k: InputValidator.sanitize_text(str(v)) if isinstance(v, str) else v
for k, v in data.items()}
with self.db.transaction() as conn:
cursor = conn.execute('''
INSERT INTO deals
(client_id, product_id, amount, status, description)
VALUES (?, ?, ?, ?, ?)
''', (
data['client_id'], data['product_id'], data['amount'],
data['status'], data.get('description')
))
deal_id = cursor.lastrowid
logger.info(f"Deal added with ID: {deal_id}.")
return deal_id
except Exception as e:
logger.error(f"Error adding deal: {str(e)}", exc_info=True)
raise DatabaseError(f"Error adding deal: {str(e)}")
def update_deal_status(self, deal_id: int, new_status: str) -> bool:
"""Update deal status"""
try:
if new_status not in self.DEAL_STATUSES:
raise ValidationError(f"Invalid deal status: {new_status}")
with self.db.transaction() as conn:
conn.execute(
'''UPDATE deals
SET status = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?''',
(new_status, deal_id)
)
logger.info(f"Deal status updated for ID {deal_id} to {new_status}.")
return True
except Exception as e:
logger.error(f"Error updating deal status: {str(e)}", exc_info=True)
raise DatabaseError(f"Error updating deal status: {str(e)}")
def add_task(self, data: Dict) -> int:
"""Add a new task"""
try:
# Validate date format
if not InputValidator.validate_date(data['due_date']):
raise ValidationError("Invalid date format")
# Sanitize text inputs
data = {k: InputValidator.sanitize_text(str(v)) if isinstance(v, str) else v
for k, v in data.items()}
with self.db.transaction() as conn:
cursor = conn.execute(
'INSERT INTO tasks (title, description, due_date, status, client_id) VALUES (?, ?, ?, ?, ?)',
(data['title'], data['description'], data['due_date'], data['status'], data.get('client_id'))
)
task_id = cursor.lastrowid
logger.info(f"Task added with ID: {task_id}.")
return task_id
except Exception as e:
logger.error(f"Error adding task: {str(e)}", exc_info=True)
raise DatabaseError(f"Error adding task: {str(e)}")
def get_client_details(self, client_id: int) -> Optional[Dict]:
"""Get comprehensive client details including deals and tasks"""
try:
client = self.get_client_by_id(client_id)
if not client:
logger.warning(f"Client details not found for ID {client_id}.")
return None
deals = self.db.execute(
'SELECT * FROM deals WHERE client_id = ?',
(client_id,)
)
deal_columns = ['id', 'client_id', 'product_id', 'amount', 'status', 'description', 'created_at', 'updated_at']
tasks = self.db.execute(
'SELECT * FROM tasks WHERE client_id = ?',
(client_id,)
)
task_columns = ['id', 'title', 'description', 'due_date', 'status', 'client_id', 'created_at']
client_details = {
'client': client,
'deals': [dict(zip(deal_columns, deal)) for deal in deals],
'tasks': [dict(zip(task_columns, task)) for task in tasks]
}
logger.info(f"Client details retrieved for ID {client_id}.")
return client_details
except Exception as e:
logger.error(f"Error retrieving client details: {str(e)}", exc_info=True)
raise DatabaseError(f"Error retrieving client details: {str(e)}")
def create_streamlit_app():
"""Create and configure the Streamlit application"""
# Set Streamlit page configuration
st.set_page_config(page_title="Enhanced CRM with AI Analytics", layout="wide")
st.title("Enhanced CRM with AI Analytics")
# Hide Streamlit's default menu and header
hide_elements = """
<style>
/* Hide Streamlit's default header and menu */
header {visibility: hidden;}
#MainMenu {visibility: hidden;}
/* Hide Plotly modebar */
.modebar {
display: none !important;
}
/* Alternative method to hide Plotly modebar */
.js-plotly-plot .plotly .modebar {
display: none !important;
}
</style>
"""
st.markdown(hide_elements, unsafe_allow_html=True)
try:
crm = CRM()
menu = ["Company Info", "Products/Services", "Clients", "Deals", "Tasks", "Analytics"]
choice = st.sidebar.selectbox("Menu", menu)
if choice == "Company Info":
st.subheader("Company Information")
show_form = st.checkbox("Show Company Info Form", key="show_company_form")
if show_form:
with st.form("company_info"):
# Get existing company info