File size: 13,658 Bytes
756c103 |
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 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Otomatik Takip ve Hatırlatma Sistemi
Müşteri taahhütlerini takip eder ve Mehmet Bey'e hatırlatır
"""
import os
import json
import logging
from datetime import datetime, timedelta
from typing import Optional, List, Dict
from dataclasses import dataclass, asdict
from enum import Enum
logger = logging.getLogger(__name__)
# Takip tipi
class FollowUpType(Enum):
RESERVATION = "reservation" # Ayırtma takibi
VISIT_PROMISE = "visit" # Gelme sözü takibi
PRICE_INQUIRY = "price" # Fiyat sorusu takibi
DECISION_PENDING = "decision" # Karar bekleyen
TEST_RIDE = "test_ride" # Test sürüşü
# Takip durumu
class FollowUpStatus(Enum):
PENDING = "pending" # Bekliyor
REMINDED = "reminded" # Hatırlatma yapıldı
COMPLETED = "completed" # Tamamlandı
CANCELLED = "cancelled" # İptal edildi
@dataclass
class FollowUp:
"""Takip kaydı"""
id: str # Unique ID
customer_phone: str # Müşteri telefonu
customer_name: Optional[str] # Müşteri adı
product_name: str # Ürün
follow_up_type: str # Takip tipi
status: str # Durum
created_at: str # Oluşturulma zamanı
follow_up_at: str # Hatırlatma zamanı
original_message: str # Orijinal mesaj
notes: Optional[str] # Notlar
store_name: Optional[str] # Mağaza
reminded_count: int = 0 # Kaç kez hatırlatıldı
class FollowUpManager:
"""Takip yöneticisi"""
def __init__(self, db_file: str = "follow_ups.json"):
self.db_file = db_file
self.follow_ups = self._load_database()
def _load_database(self) -> List[FollowUp]:
"""Database'i yükle"""
if os.path.exists(self.db_file):
try:
with open(self.db_file, "r") as f:
data = json.load(f)
return [FollowUp(**item) for item in data]
except Exception as e:
logger.error(f"Database yükleme hatası: {e}")
return []
return []
def _save_database(self):
"""Database'i kaydet"""
try:
data = [asdict(f) for f in self.follow_ups]
with open(self.db_file, "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
except Exception as e:
logger.error(f"Database kayıt hatası: {e}")
def create_follow_up(
self,
customer_phone: str,
product_name: str,
follow_up_type: FollowUpType,
original_message: str,
follow_up_hours: int = 24,
customer_name: Optional[str] = None,
notes: Optional[str] = None,
store_name: Optional[str] = None
) -> FollowUp:
"""Yeni takip oluştur"""
now = datetime.now()
follow_up_time = now + timedelta(hours=follow_up_hours)
# Unique ID oluştur
follow_up_id = f"{customer_phone}_{now.strftime('%Y%m%d_%H%M%S')}"
follow_up = FollowUp(
id=follow_up_id,
customer_phone=customer_phone,
customer_name=customer_name,
product_name=product_name,
follow_up_type=follow_up_type.value,
status=FollowUpStatus.PENDING.value,
created_at=now.isoformat(),
follow_up_at=follow_up_time.isoformat(),
original_message=original_message,
notes=notes,
store_name=store_name,
reminded_count=0
)
self.follow_ups.append(follow_up)
self._save_database()
logger.info(f"✅ Takip oluşturuldu: {follow_up_id}")
logger.info(f" Hatırlatma zamanı: {follow_up_time.strftime('%d.%m.%Y %H:%M')}")
return follow_up
def get_pending_reminders(self) -> List[FollowUp]:
"""Bekleyen hatırlatmaları getir"""
now = datetime.now()
pending = []
for follow_up in self.follow_ups:
if follow_up.status == FollowUpStatus.PENDING.value:
follow_up_time = datetime.fromisoformat(follow_up.follow_up_at)
if follow_up_time <= now:
pending.append(follow_up)
return pending
def mark_as_reminded(self, follow_up_id: str):
"""Hatırlatma yapıldı olarak işaretle"""
for follow_up in self.follow_ups:
if follow_up.id == follow_up_id:
follow_up.status = FollowUpStatus.REMINDED.value
follow_up.reminded_count += 1
self._save_database()
logger.info(f"✅ Hatırlatma yapıldı: {follow_up_id}")
break
def mark_as_completed(self, follow_up_id: str):
"""Tamamlandı olarak işaretle"""
for follow_up in self.follow_ups:
if follow_up.id == follow_up_id:
follow_up.status = FollowUpStatus.COMPLETED.value
self._save_database()
logger.info(f"✅ Takip tamamlandı: {follow_up_id}")
break
def get_customer_history(self, customer_phone: str) -> List[FollowUp]:
"""Müşteri geçmişini getir"""
return [f for f in self.follow_ups if f.customer_phone == customer_phone]
def get_todays_follow_ups(self) -> List[FollowUp]:
"""Bugünün takiplerini getir"""
today = datetime.now().date()
todays = []
for follow_up in self.follow_ups:
follow_up_date = datetime.fromisoformat(follow_up.follow_up_at).date()
if follow_up_date == today:
todays.append(follow_up)
return todays
def analyze_message_for_follow_up(message: str) -> Optional[Dict]:
"""
Mesajı analiz et ve takip gerekip gerekmediğini belirle
Returns:
{
"needs_follow_up": True/False,
"follow_up_type": FollowUpType,
"follow_up_hours": int,
"reason": str
}
"""
message_lower = message.lower()
# YARIN gelme sözleri (24 saat sonra hatırlat)
tomorrow_keywords = [
'yarın', 'yarin',
'yarın gel', 'yarın al', 'yarın uğra',
'yarına', 'yarina',
'ertesi gün'
]
# BUGÜN gelme sözleri (6 saat sonra hatırlat)
today_keywords = [
'bugün', 'bugun',
'bugün gel', 'bugün al', 'bugün uğra',
'akşam gel', 'aksam gel',
'öğleden sonra', 'ogleden sonra',
'birazdan', 'biraz sonra',
'1 saat', 'bir saat',
'2 saat', 'iki saat',
'30 dakika', 'yarım saat'
]
# HAFTA SONU gelme sözleri
weekend_keywords = [
'hafta sonu', 'haftasonu',
'cumartesi', 'pazar',
'hafta içi', 'haftaiçi'
]
# KARAR VERME sözleri (48 saat sonra hatırlat)
decision_keywords = [
'düşüneyim', 'düşüncem', 'düşünelim',
'danışayım', 'danısayım', 'danışıcam',
'eşime sor', 'eşimle konuş', 'esime sor',
'karar ver', 'haber ver',
'araştırayım', 'araştırıcam',
'bakarım', 'bakarız', 'bakıcam'
]
# TEST SÜRÜŞÜ (4 saat sonra hatırlat)
test_keywords = [
'test sürüş', 'test et', 'dene',
'binebilir', 'binmek ist',
'test ride', 'deneme sürüş'
]
# Yarın kontrolü
for keyword in tomorrow_keywords:
if keyword in message_lower:
return {
"needs_follow_up": True,
"follow_up_type": FollowUpType.VISIT_PROMISE,
"follow_up_hours": 24,
"reason": f"Müşteri yarın geleceğini söyledi: '{keyword}'"
}
# Bugün kontrolü
for keyword in today_keywords:
if keyword in message_lower:
return {
"needs_follow_up": True,
"follow_up_type": FollowUpType.VISIT_PROMISE,
"follow_up_hours": 6,
"reason": f"Müşteri bugün geleceğini söyledi: '{keyword}'"
}
# Hafta sonu kontrolü
for keyword in weekend_keywords:
if keyword in message_lower:
# Bugün hangi gün?
today = datetime.now().weekday() # 0=Pazartesi, 6=Pazar
if today < 5: # Hafta içiyse
days_to_saturday = 5 - today
hours = days_to_saturday * 24
else: # Zaten hafta sonuysa
hours = 24
return {
"needs_follow_up": True,
"follow_up_type": FollowUpType.VISIT_PROMISE,
"follow_up_hours": hours,
"reason": f"Müşteri hafta sonu geleceğini söyledi: '{keyword}'"
}
# Karar verme kontrolü
for keyword in decision_keywords:
if keyword in message_lower:
return {
"needs_follow_up": True,
"follow_up_type": FollowUpType.DECISION_PENDING,
"follow_up_hours": 48,
"reason": f"Müşteri düşüneceğini söyledi: '{keyword}'"
}
# Test sürüşü kontrolü
for keyword in test_keywords:
if keyword in message_lower:
return {
"needs_follow_up": True,
"follow_up_type": FollowUpType.TEST_RIDE,
"follow_up_hours": 4,
"reason": f"Müşteri test sürüşü istiyor: '{keyword}'"
}
# Ayırtma varsa 24 saat sonra kontrol
reservation_keywords = ['ayırt', 'rezerve', 'tutun', 'sakla']
for keyword in reservation_keywords:
if keyword in message_lower:
return {
"needs_follow_up": True,
"follow_up_type": FollowUpType.RESERVATION,
"follow_up_hours": 24,
"reason": f"Ayırtma talebi var: '{keyword}'"
}
return None
def format_reminder_message(follow_up: FollowUp) -> str:
"""Hatırlatma mesajını formatla"""
# Takip tipine göre emoji
type_emojis = {
"reservation": "📦",
"visit": "🚶",
"price": "💰",
"decision": "🤔",
"test_ride": "🚴"
}
emoji = type_emojis.get(follow_up.follow_up_type, "📌")
# Zaman hesaplama
created_time = datetime.fromisoformat(follow_up.created_at)
time_diff = datetime.now() - created_time
if time_diff.days > 0:
time_str = f"{time_diff.days} gün önce"
elif time_diff.seconds > 3600:
hours = time_diff.seconds // 3600
time_str = f"{hours} saat önce"
else:
time_str = "Az önce"
# Mesaj oluştur
message = f"""
{emoji} **TAKİP HATIRLATMASI**
👤 Müşteri: {follow_up.customer_name or "İsimsiz"}
📱 Tel: {follow_up.customer_phone.replace('whatsapp:', '')}
🚲 Ürün: {follow_up.product_name}
⏰ İlk mesaj: {time_str}
📝 Müşteri mesajı:
"{follow_up.original_message}"
"""
# Tipe göre özel mesaj
if follow_up.follow_up_type == "reservation":
message += "\n⚠️ AYIRTMA TAKİBİ: Müşteri geldi mi?"
elif follow_up.follow_up_type == "visit":
message += "\n⚠️ ZİYARET TAKİBİ: Müşteri geleceğini söylemişti"
elif follow_up.follow_up_type == "decision":
message += "\n⚠️ KARAR TAKİBİ: Müşteri düşüneceğini söylemişti"
elif follow_up.follow_up_type == "test_ride":
message += "\n⚠️ TEST SÜRÜŞÜ TAKİBİ: Test için gelecekti"
message += "\n\n📞 Müşteriyi arayıp durumu öğrenin!"
return message
# Test fonksiyonu
def test_follow_up_system():
"""Test senaryoları"""
print("\n" + "="*60)
print("TAKİP SİSTEMİ TESTİ")
print("="*60)
manager = FollowUpManager("test_follow_ups.json")
# Test mesajları
test_messages = [
("Yarın gelip FX 2'yi alacağım", "FX 2"),
("Eşime danışayım, size dönerim", "Marlin 5"),
("Bugün akşam uğrarım", "Checkpoint"),
("Hafta sonu test sürüşü yapabilir miyim?", "Domane"),
("30 dakikaya oradayım, ayırtın", "FX Sport")
]
for message, product in test_messages:
print(f"\n📝 Mesaj: '{message}'")
analysis = analyze_message_for_follow_up(message)
if analysis and analysis["needs_follow_up"]:
print(f"✅ Takip gerekli!")
print(f" Tip: {analysis['follow_up_type'].value}")
print(f" {analysis['follow_up_hours']} saat sonra hatırlat")
print(f" Sebep: {analysis['reason']}")
# Takip oluştur
follow_up = manager.create_follow_up(
customer_phone="whatsapp:+905551234567",
product_name=product,
follow_up_type=analysis["follow_up_type"],
original_message=message,
follow_up_hours=analysis["follow_up_hours"]
)
else:
print("❌ Takip gerekmiyor")
# Bekleyen hatırlatmaları göster
print("\n" + "="*60)
print("BEKLEYEN HATIRLATMALAR")
print("="*60)
pending = manager.get_pending_reminders()
if pending:
for f in pending:
print(f"\n{format_reminder_message(f)}")
else:
print("Bekleyen hatırlatma yok")
print("\n" + "="*60)
if __name__ == "__main__":
test_follow_up_system() |