Add warehouse stock integration to BF desktop chatbot
Browse files- Integrated B2B warehouse API with context-aware variant search
- Added warehouse stock information to product responses
- Shows which stores have products in stock (without quantities)
- Works with both improved search and basic search
- Context-aware: 'Marlin 6 M Turuncu' finds only Marlin 6 variants
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
app.py
CHANGED
|
@@ -29,6 +29,164 @@ from enhanced_features import (
|
|
| 29 |
)
|
| 30 |
from image_renderer import extract_product_info_for_gallery, format_message_with_images
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
# Import improved product search
|
| 33 |
try:
|
| 34 |
from improved_chatbot import ImprovedChatbot
|
|
@@ -336,9 +494,30 @@ def chatbot_fn(user_message, history, image=None):
|
|
| 336 |
try:
|
| 337 |
product_result = improved_bot.process_message(user_message)
|
| 338 |
if product_result['is_product_query'] and product_result['response']:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
system_messages.append({
|
| 340 |
"role": "system",
|
| 341 |
-
"content": f"ÜRÜN BİLGİSİ:\n{
|
| 342 |
})
|
| 343 |
product_found_improved = True
|
| 344 |
except Exception as e:
|
|
@@ -402,8 +581,21 @@ def chatbot_fn(user_message, history, image=None):
|
|
| 402 |
if len(product_info[1]) > 6 and product_info[1][6]: # Resim URL'si varsa
|
| 403 |
product_image = f"\\nÜrün resmi: {product_info[1][6]}"
|
| 404 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 405 |
# Tüm bilgileri birleştir
|
| 406 |
-
new_msg = f"{product_info[2]} {product_info[1][0]}\\n{normal_price}{rebate_price}{discount_info}{eft_price}{rebate_money_order_price}{product_link}{product_image}"
|
| 407 |
else:
|
| 408 |
# Ürün stokta yoksa sadece stok durumunu bildir
|
| 409 |
new_msg = f"{product_info[2]} {product_info[1][0]}"
|
|
|
|
| 29 |
)
|
| 30 |
from image_renderer import extract_product_info_for_gallery, format_message_with_images
|
| 31 |
|
| 32 |
+
# Warehouse stock integration
|
| 33 |
+
def get_warehouse_stock(product_name):
|
| 34 |
+
"""B2B API'den mağaza stok bilgilerini çek - BF Space integration"""
|
| 35 |
+
try:
|
| 36 |
+
import re
|
| 37 |
+
warehouse_url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml.php'
|
| 38 |
+
response = requests.get(warehouse_url, verify=False, timeout=15)
|
| 39 |
+
|
| 40 |
+
if response.status_code != 200:
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
root = ET.fromstring(response.content)
|
| 44 |
+
|
| 45 |
+
# Turkish character normalization function
|
| 46 |
+
turkish_map = {'ı': 'i', 'ğ': 'g', 'ü': 'u', 'ş': 's', 'ö': 'o', 'ç': 'c', 'İ': 'i', 'I': 'i'}
|
| 47 |
+
|
| 48 |
+
def normalize_turkish(text):
|
| 49 |
+
import unicodedata
|
| 50 |
+
text = unicodedata.normalize('NFD', text)
|
| 51 |
+
text = ''.join(char for char in text if unicodedata.category(char) != 'Mn')
|
| 52 |
+
for tr_char, en_char in turkish_map.items():
|
| 53 |
+
text = text.replace(tr_char, en_char)
|
| 54 |
+
return text
|
| 55 |
+
|
| 56 |
+
# Normalize search product name
|
| 57 |
+
search_name = normalize_turkish(product_name.lower().strip())
|
| 58 |
+
search_name = search_name.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
|
| 59 |
+
search_words = search_name.split()
|
| 60 |
+
|
| 61 |
+
# Separate size/color words from product words
|
| 62 |
+
size_color_words = ['s', 'm', 'l', 'xl', 'xs', 'small', 'medium', 'large',
|
| 63 |
+
'turuncu', 'siyah', 'beyaz', 'mavi', 'kirmizi', 'yesil',
|
| 64 |
+
'orange', 'black', 'white', 'blue', 'red', 'green']
|
| 65 |
+
|
| 66 |
+
variant_words = [word for word in search_words if word in size_color_words]
|
| 67 |
+
product_words = [word for word in search_words if word not in size_color_words]
|
| 68 |
+
|
| 69 |
+
# Check if this is a size/color specific query
|
| 70 |
+
is_size_color_query = len(variant_words) > 0 and len(search_words) <= 4
|
| 71 |
+
|
| 72 |
+
best_matches = []
|
| 73 |
+
exact_matches = []
|
| 74 |
+
variant_matches = []
|
| 75 |
+
candidates = []
|
| 76 |
+
|
| 77 |
+
# First pass: Variant field search for size/color combinations
|
| 78 |
+
if is_size_color_query:
|
| 79 |
+
for product in root.findall('Product'):
|
| 80 |
+
product_name_elem = product.find('ProductName')
|
| 81 |
+
variant_elem = product.find('Variant')
|
| 82 |
+
|
| 83 |
+
if product_name_elem is not None and product_name_elem.text:
|
| 84 |
+
xml_product_name = product_name_elem.text.strip()
|
| 85 |
+
normalized_product_name = normalize_turkish(xml_product_name.lower())
|
| 86 |
+
|
| 87 |
+
# If there are product words, check if they match the product name
|
| 88 |
+
product_name_matches = True
|
| 89 |
+
if product_words:
|
| 90 |
+
product_name_matches = all(word in normalized_product_name for word in product_words)
|
| 91 |
+
|
| 92 |
+
# Only proceed if product name matches (or no product context)
|
| 93 |
+
if product_name_matches:
|
| 94 |
+
# Variant field check
|
| 95 |
+
if variant_elem is not None and variant_elem.text:
|
| 96 |
+
variant_text = normalize_turkish(variant_elem.text.lower().replace('-', ' '))
|
| 97 |
+
|
| 98 |
+
# Check if all variant words are in variant field
|
| 99 |
+
if all(word in variant_text for word in variant_words):
|
| 100 |
+
variant_matches.append((product, xml_product_name, variant_text))
|
| 101 |
+
|
| 102 |
+
if variant_matches:
|
| 103 |
+
candidates = variant_matches
|
| 104 |
+
else:
|
| 105 |
+
# Fallback to normal product name search
|
| 106 |
+
is_size_color_query = False
|
| 107 |
+
|
| 108 |
+
# Second pass: Normal product name exact matches (if no variant match)
|
| 109 |
+
if not is_size_color_query or not candidates:
|
| 110 |
+
for product in root.findall('Product'):
|
| 111 |
+
product_name_elem = product.find('ProductName')
|
| 112 |
+
if product_name_elem is not None and product_name_elem.text:
|
| 113 |
+
xml_product_name = product_name_elem.text.strip()
|
| 114 |
+
normalized_xml = normalize_turkish(xml_product_name.lower())
|
| 115 |
+
normalized_xml = normalized_xml.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
|
| 116 |
+
xml_words = normalized_xml.split()
|
| 117 |
+
|
| 118 |
+
# Exact match check - first two words must match exactly
|
| 119 |
+
if len(search_words) >= 2 and len(xml_words) >= 2:
|
| 120 |
+
search_key = f"{search_words[0]} {search_words[1]}"
|
| 121 |
+
xml_key = f"{xml_words[0]} {xml_words[1]}"
|
| 122 |
+
|
| 123 |
+
if search_key == xml_key:
|
| 124 |
+
exact_matches.append((product, xml_product_name, normalized_xml))
|
| 125 |
+
|
| 126 |
+
# Use variant matches if available, otherwise exact matches
|
| 127 |
+
if not candidates:
|
| 128 |
+
candidates = exact_matches if exact_matches else []
|
| 129 |
+
|
| 130 |
+
# If still no matches, try fuzzy matching
|
| 131 |
+
if not candidates:
|
| 132 |
+
for product in root.findall('Product'):
|
| 133 |
+
product_name_elem = product.find('ProductName')
|
| 134 |
+
if product_name_elem is not None and product_name_elem.text:
|
| 135 |
+
xml_product_name = product_name_elem.text.strip()
|
| 136 |
+
normalized_xml = normalize_turkish(xml_product_name.lower())
|
| 137 |
+
normalized_xml = normalized_xml.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
|
| 138 |
+
xml_words = normalized_xml.split()
|
| 139 |
+
|
| 140 |
+
# Count common words
|
| 141 |
+
common_words = set(search_words) & set(xml_words)
|
| 142 |
+
|
| 143 |
+
# Need at least 2 common words AND first word must match (brand check)
|
| 144 |
+
if (len(common_words) >= 2 and
|
| 145 |
+
len(search_words) > 0 and len(xml_words) > 0 and
|
| 146 |
+
search_words[0] == xml_words[0]):
|
| 147 |
+
best_matches.append((product, xml_product_name, normalized_xml, len(common_words)))
|
| 148 |
+
|
| 149 |
+
# Select those with most common words
|
| 150 |
+
if best_matches:
|
| 151 |
+
max_common = max(match[3] for match in best_matches)
|
| 152 |
+
candidates = [(match[0], match[1], match[2]) for match in best_matches if match[3] == max_common]
|
| 153 |
+
|
| 154 |
+
# Collect stock info and prevent duplicates
|
| 155 |
+
warehouse_stock_map = {} # warehouse_name -> total_stock
|
| 156 |
+
|
| 157 |
+
for product, xml_name, _ in candidates:
|
| 158 |
+
warehouses = product.find('Warehouses')
|
| 159 |
+
if warehouses is not None:
|
| 160 |
+
for warehouse in warehouses.findall('Warehouse'):
|
| 161 |
+
name_elem = warehouse.find('Name')
|
| 162 |
+
stock_elem = warehouse.find('Stock')
|
| 163 |
+
|
| 164 |
+
if name_elem is not None and stock_elem is not None:
|
| 165 |
+
warehouse_name = name_elem.text if name_elem.text else "Bilinmeyen"
|
| 166 |
+
try:
|
| 167 |
+
stock_count = int(stock_elem.text) if stock_elem.text else 0
|
| 168 |
+
if stock_count > 0:
|
| 169 |
+
# Sum stocks for same warehouse
|
| 170 |
+
if warehouse_name in warehouse_stock_map:
|
| 171 |
+
warehouse_stock_map[warehouse_name] += stock_count
|
| 172 |
+
else:
|
| 173 |
+
warehouse_stock_map[warehouse_name] = stock_count
|
| 174 |
+
except (ValueError, TypeError):
|
| 175 |
+
pass
|
| 176 |
+
|
| 177 |
+
if warehouse_stock_map:
|
| 178 |
+
# Return warehouse stock as list
|
| 179 |
+
all_warehouse_info = []
|
| 180 |
+
for warehouse_name, total_stock in warehouse_stock_map.items():
|
| 181 |
+
all_warehouse_info.append(f"{warehouse_name}: Stokta var")
|
| 182 |
+
return all_warehouse_info
|
| 183 |
+
else:
|
| 184 |
+
return ["Hiçbir mağazada stokta bulunmuyor"]
|
| 185 |
+
|
| 186 |
+
except Exception as e:
|
| 187 |
+
print(f"Mağaza stok bilgisi çekme hatası: {e}")
|
| 188 |
+
return None
|
| 189 |
+
|
| 190 |
# Import improved product search
|
| 191 |
try:
|
| 192 |
from improved_chatbot import ImprovedChatbot
|
|
|
|
| 494 |
try:
|
| 495 |
product_result = improved_bot.process_message(user_message)
|
| 496 |
if product_result['is_product_query'] and product_result['response']:
|
| 497 |
+
# Extract product name from improved search result for warehouse stock
|
| 498 |
+
enhanced_response = product_result['response']
|
| 499 |
+
|
| 500 |
+
# Try to get warehouse stock info
|
| 501 |
+
try:
|
| 502 |
+
# Extract product name from the response - look for product names in user message
|
| 503 |
+
input_words = user_message.lower().split()
|
| 504 |
+
warehouse_info = ""
|
| 505 |
+
|
| 506 |
+
# Try warehouse stock with the user's original query
|
| 507 |
+
warehouse_stock = get_warehouse_stock(user_message)
|
| 508 |
+
if warehouse_stock and warehouse_stock != ["Hiçbir mağazada stokta bulunmuyor"]:
|
| 509 |
+
warehouse_info = f"\n\n🏪 MAĞAZA STOK BİLGİLERİ:\n"
|
| 510 |
+
for store_info in warehouse_stock:
|
| 511 |
+
warehouse_info += f"• {store_info}\n"
|
| 512 |
+
enhanced_response += warehouse_info
|
| 513 |
+
elif warehouse_stock == ["Hiçbir mağazada stokta bulunmuyor"]:
|
| 514 |
+
enhanced_response += f"\n\n🏪 MAĞAZA STOK BİLGİLERİ: Hiçbir mağazada stokta bulunmuyor"
|
| 515 |
+
except Exception as e:
|
| 516 |
+
print(f"Warehouse stock error in improved search: {e}")
|
| 517 |
+
|
| 518 |
system_messages.append({
|
| 519 |
"role": "system",
|
| 520 |
+
"content": f"ÜRÜN BİLGİSİ:\n{enhanced_response}\n\nBu bilgileri kullanarak kullanıcıya yardımcı ol."
|
| 521 |
})
|
| 522 |
product_found_improved = True
|
| 523 |
except Exception as e:
|
|
|
|
| 581 |
if len(product_info[1]) > 6 and product_info[1][6]: # Resim URL'si varsa
|
| 582 |
product_image = f"\\nÜrün resmi: {product_info[1][6]}"
|
| 583 |
|
| 584 |
+
# Mağaza stok bilgilerini ekle
|
| 585 |
+
warehouse_stock_info = ""
|
| 586 |
+
try:
|
| 587 |
+
warehouse_stock = get_warehouse_stock(product_info[2])
|
| 588 |
+
if warehouse_stock and warehouse_stock != ["Hiçbir mağazada stokta bulunmuyor"]:
|
| 589 |
+
warehouse_stock_info = f"\\n🏪 Mağaza stok bilgileri:\\n"
|
| 590 |
+
for store_info in warehouse_stock:
|
| 591 |
+
warehouse_stock_info += f"• {store_info}\\n"
|
| 592 |
+
elif warehouse_stock == ["Hiçbir mağazada stokta bulunmuyor"]:
|
| 593 |
+
warehouse_stock_info = f"\\n🏪 Mağaza stok bilgileri: Hiçbir mağazada stokta bulunmuyor\\n"
|
| 594 |
+
except Exception as e:
|
| 595 |
+
print(f"Warehouse stock error for {product_info[2]}: {e}")
|
| 596 |
+
|
| 597 |
# Tüm bilgileri birleştir
|
| 598 |
+
new_msg = f"{product_info[2]} {product_info[1][0]}\\n{normal_price}{rebate_price}{discount_info}{eft_price}{rebate_money_order_price}{product_link}{product_image}{warehouse_stock_info}"
|
| 599 |
else:
|
| 600 |
# Ürün stokta yoksa sadece stok durumunu bildir
|
| 601 |
new_msg = f"{product_info[2]} {product_info[1][0]}"
|