BF-WAB / whatsapp_renderer.py
SamiKoen's picture
Upload 4 files
a945de6 verified
raw
history blame
8.4 kB
# -*- coding: utf-8 -*-
"""
WhatsApp Ürün Resimlerini ve Karşılaştırmalarını Gösterme Sistemi
WhatsApp için basitleştirilmiş versiyon - Sadece URL paylaşımı
"""
def round_price(price_str):
"""Fiyatı yuvarlama formülüne göre yuvarla"""
try:
# TL ve diğer karakterleri temizle
price_clean = price_str.replace(' TL', '').replace(',', '.')
price_float = float(price_clean)
# Fiyat 200000 üzerindeyse en yakın 5000'lik basamağa yuvarla
if price_float > 200000:
return str(round(price_float / 5000) * 5000)
# Fiyat 30000 üzerindeyse en yakın 1000'lik basamağa yuvarla
elif price_float > 30000:
return str(round(price_float / 1000) * 1000)
# Fiyat 10000 üzerindeyse en yakın 100'lük basamağa yuvarla
elif price_float > 10000:
return str(round(price_float / 100) * 100)
# Diğer durumlarda en yakın 10'luk basamağa yuvarla
else:
return str(round(price_float / 10) * 10)
except (ValueError, TypeError):
return price_str
def format_message_with_images_whatsapp(message):
"""WhatsApp için mesajdaki resim URL'lerini formatla"""
if "Ürün resmi:" not in message:
return message
lines = message.split('\n')
formatted_lines = []
for line in lines:
if line.startswith("Ürün resmi:"):
image_url = line.replace("Ürün resmi:", "").strip()
if image_url:
# WhatsApp için sadece URL'yi ekle - WhatsApp otomatik önizleme yapar
formatted_lines.append(f"🖼️ Ürün Resmi: {image_url}")
else:
formatted_lines.append(line)
else:
formatted_lines.append(line)
return '\n'.join(formatted_lines)
def create_product_comparison_whatsapp(products_with_info):
"""WhatsApp için ürün karşılaştırması oluştur"""
if not products_with_info:
return ""
comparison_text = "📊 **ÜRÜN KARŞILAŞTIRMASI**\n\n"
for i, product in enumerate(products_with_info, 1):
name = product.get('name', 'Bilinmeyen')
price = product.get('price', 'Fiyat yok')
stock = product.get('stock', 'Stok bilgisi yok')
product_url = product.get('product_url', '')
image_url = product.get('image_url', '')
comparison_text += f"**{i}. {name}**\n"
comparison_text += f"💰 Fiyat: {price}\n"
comparison_text += f"📦 Stok: {stock}\n"
if image_url:
comparison_text += f"🖼️ Resim: {image_url}\n"
if product_url:
comparison_text += f"🔗 Link: {product_url}\n"
comparison_text += "\n" + "─" * 30 + "\n\n"
return comparison_text
def extract_product_info_whatsapp(message):
"""WhatsApp mesajından ürün bilgilerini çıkar ve formatla"""
# Önce resim URL'lerini formatla
formatted_message = format_message_with_images_whatsapp(message)
# Karşılaştırma veya öneri mesajı ise özel formatla
if any(keyword in message.lower() for keyword in ["karşılaştır", "öneri", "seçenek", "alternatif", "bütçe"]):
# Ürün listesi var mı kontrol et
lines = message.split('\n')
products = []
current_product = {}
for line in lines:
line = line.strip()
if line.startswith('•') and any(keyword in line.lower() for keyword in ['marlin', 'émonda', 'madone', 'domane', 'fuel', 'powerfly', 'fx']):
# Yeni ürün başladı
if current_product:
products.append(current_product)
# Ürün adı ve fiyatı parse et
parts = line.split(' - ')
name = parts[0].replace('•', '').strip()
price_raw = parts[1] if len(parts) > 1 else 'Fiyat yok'
# Fiyatı yuvarlama formülüne göre yuvarla
if price_raw != 'Fiyat yok':
price = round_price(price_raw) + ' TL'
else:
price = price_raw
current_product = {
'name': name,
'price': price,
'stock': 'stokta',
'image_url': '',
'product_url': ''
}
elif "Ürün resmi:" in line and current_product:
current_product['image_url'] = line.replace("Ürün resmi:", "").strip()
elif "Ürün linki:" in line and current_product:
current_product['product_url'] = line.replace("Ürün linki:", "").strip()
# Son ürünü ekle
if current_product:
products.append(current_product)
if len(products) > 1:
# Çoklu ürün karşılaştırması
comparison = create_product_comparison_whatsapp(products)
# Orijinal mesajdaki resim linklerini temizle
cleaned_message = message
for line in message.split('\n'):
if line.startswith("Ürün resmi:") or line.startswith("Ürün linki:"):
cleaned_message = cleaned_message.replace(line, "")
return cleaned_message.strip() + "\n\n" + comparison
return formatted_message
def should_use_comparison_format_whatsapp(message):
"""WhatsApp mesajının karşılaştırma formatı kullanması gerekip gerekmediğini kontrol et"""
comparison_keywords = ["karşılaştır", "öneri", "seçenek", "alternatif", "bütçe", "compare"]
return any(keyword in message.lower() for keyword in comparison_keywords)
def format_whatsapp_product_list(products, title="Ürün Listesi"):
"""WhatsApp için ürün listesini formatla"""
if not products:
return f"❌ {title} - Uygun ürün bulunamadı."
text = f"🚲 **{title.upper()}**\n\n"
for i, product in enumerate(products, 1):
name, item_info, full_name = product
price = item_info[1] if len(item_info) > 1 else "Fiyat yok"
product_link = item_info[2] if len(item_info) > 2 else ""
text += f"**{i}. {full_name}**\n"
text += f"💰 {price} TL\n"
# Resim URL'si varsa ekle
if len(item_info) > 6 and item_info[6]:
text += f"🖼️ {item_info[6]}\n"
if product_link:
text += f"🔗 {product_link}\n"
text += "\n"
return text
def format_whatsapp_single_product(product):
"""WhatsApp için tek ürün formatla"""
if not product:
return "❌ Ürün bulunamadı."
name, item_info, full_name = product
text = f"🚲 **{full_name}**\n\n"
# Stok durumu
stock_status = item_info[0] if len(item_info) > 0 else "Bilgi yok"
text += f"📦 Stok: {stock_status}\n"
if stock_status == "stokta":
# Fiyat bilgileri
if len(item_info) > 1 and item_info[1]:
text += f"💰 Fiyat: {item_info[1]} TL\n"
# EFT fiyatı
if len(item_info) > 3 and item_info[3]:
text += f"💳 Havale Fiyatı: {item_info[3]} TL\n"
# Kampanyalı fiyat
if len(item_info) > 4 and item_info[4]:
text += f"🎯 Kampanyalı Fiyat: {item_info[4]} TL\n"
# Resim
if len(item_info) > 6 and item_info[6]:
text += f"🖼️ {item_info[6]}\n"
# Ürün linki
if len(item_info) > 2 and item_info[2]:
text += f"🔗 {item_info[2]}\n"
return text
def clean_whatsapp_message(message):
"""WhatsApp mesajını temizle ve optimize et"""
# Gereksiz boşlukları temizle
lines = [line.strip() for line in message.split('\n') if line.strip()]
# Aynı URL'leri tekrar eden satırları kaldır
seen_urls = set()
clean_lines = []
for line in lines:
if line.startswith('🖼️') or line.startswith('🔗'):
url = line.split(' ', 1)[1] if ' ' in line else line
if url not in seen_urls:
seen_urls.add(url)
clean_lines.append(line)
else:
clean_lines.append(line)
return '\n'.join(clean_lines)