File size: 8,163 Bytes
4fa4ebe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import requests
import xml.etree.ElementTree as ET

def get_warehouse_stock(product_name):
    """B2B API'den mağaza stok bilgilerini çek - Final Updated Version"""
    try:
        import re
        warehouse_url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml.php'
        response = requests.get(warehouse_url, verify=False, timeout=15)
        
        if response.status_code != 200:
            return None
            
        root = ET.fromstring(response.content)
        
        # Turkish character normalization function
        turkish_map = {'ı': 'i', 'ğ': 'g', 'ü': 'u', 'ş': 's', 'ö': 'o', 'ç': 'c', 'İ': 'i', 'I': 'i'}
        
        def normalize_turkish(text):
            import unicodedata
            text = unicodedata.normalize('NFD', text)
            text = ''.join(char for char in text if unicodedata.category(char) != 'Mn')
            for tr_char, en_char in turkish_map.items():
                text = text.replace(tr_char, en_char)
            return text
        
        # Normalize search product name
        search_name = normalize_turkish(product_name.lower().strip())
        search_name = search_name.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
        search_words = search_name.split()
        
        best_matches = []
        exact_matches = []
        variant_matches = []
        candidates = []
        
        # Check if this is a size/color specific query (like "M Turuncu")
        is_size_color_query = (len(search_words) <= 3 and 
                               any(word in ['s', 'm', 'l', 'xl', 'xs', 'small', 'medium', 'large', 
                                           'turuncu', 'siyah', 'beyaz', 'mavi', 'kirmizi', 'yesil', 
                                           'orange', 'black', 'white', 'blue', 'red', 'green'] 
                                   for word in search_words))
        
        # İlk geçiş: Variant alanında beden/renk araması
        if is_size_color_query:
            for product in root.findall('Product'):
                product_name_elem = product.find('ProductName')
                variant_elem = product.find('Variant')
                
                if product_name_elem is not None and product_name_elem.text:
                    xml_product_name = product_name_elem.text.strip()
                    
                    # Variant field check
                    if variant_elem is not None and variant_elem.text:
                        variant_text = normalize_turkish(variant_elem.text.lower().replace('-', ' '))
                        
                        # Check if all search words are in variant field
                        if all(word in variant_text for word in search_words):
                            variant_matches.append((product, xml_product_name, variant_text))
            
            if variant_matches:
                candidates = variant_matches
            else:
                # Fallback to normal product name search
                is_size_color_query = False
        
        # İkinci geçiş: Normal ürün adı tam eşleşmeleri (variant match yoksa)
        if not is_size_color_query or not candidates:
            for product in root.findall('Product'):
                product_name_elem = product.find('ProductName')
                if product_name_elem is not None and product_name_elem.text:
                    xml_product_name = product_name_elem.text.strip()
                    normalized_xml = normalize_turkish(xml_product_name.lower())
                    normalized_xml = normalized_xml.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
                    xml_words = normalized_xml.split()
                    
                    # Tam eşleşme kontrolü - ilk iki kelime tam aynı olmalı
                    if len(search_words) >= 2 and len(xml_words) >= 2:
                        search_key = f"{search_words[0]} {search_words[1]}"
                        xml_key = f"{xml_words[0]} {xml_words[1]}"
                        
                        if search_key == xml_key:
                            exact_matches.append((product, xml_product_name, normalized_xml))
            
            # Eğer variant match varsa onu kullan, yoksa exact matches kullan
            if not candidates:
                candidates = exact_matches if exact_matches else []
        
        # Eğer hala bir match yoksa, fuzzy matching yap
        if not candidates:
            for product in root.findall('Product'):
                product_name_elem = product.find('ProductName')
                if product_name_elem is not None and product_name_elem.text:
                    xml_product_name = product_name_elem.text.strip()
                    normalized_xml = normalize_turkish(xml_product_name.lower())
                    normalized_xml = normalized_xml.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
                    xml_words = normalized_xml.split()
                    
                    # Ortak kelime sayısını hesapla
                    common_words = set(search_words) & set(xml_words)
                    
                    # En az 2 ortak kelime olmalı VE ilk kelime aynı olmalı (marka kontrolü)
                    if (len(common_words) >= 2 and 
                        len(search_words) > 0 and len(xml_words) > 0 and 
                        search_words[0] == xml_words[0]):
                        best_matches.append((product, xml_product_name, normalized_xml, len(common_words)))
            
            # En çok ortak kelimeye sahip olanları seç
            if best_matches:
                max_common = max(match[3] for match in best_matches)
                candidates = [(match[0], match[1], match[2]) for match in best_matches if match[3] == max_common]
        
        # Stok bilgilerini topla ve tekrarları önle
        warehouse_stock_map = {}  # warehouse_name -> total_stock
        
        for product, xml_name, _ in candidates:
            warehouses = product.find('Warehouses')
            if warehouses is not None:
                for warehouse in warehouses.findall('Warehouse'):
                    name_elem = warehouse.find('Name')
                    stock_elem = warehouse.find('Stock')
                    
                    if name_elem is not None and stock_elem is not None:
                        warehouse_name = name_elem.text if name_elem.text else "Bilinmeyen"
                        try:
                            stock_count = int(stock_elem.text) if stock_elem.text else 0
                            if stock_count > 0:
                                # Aynı mağaza için stokları topla
                                if warehouse_name in warehouse_stock_map:
                                    warehouse_stock_map[warehouse_name] += stock_count
                                else:
                                    warehouse_stock_map[warehouse_name] = stock_count
                        except (ValueError, TypeError):
                            pass
        
        if warehouse_stock_map:
            # Mağaza stoklarını liste halinde döndür
            all_warehouse_info = []
            for warehouse_name, total_stock in warehouse_stock_map.items():
                all_warehouse_info.append(f"{warehouse_name}: {total_stock} adet")
            return all_warehouse_info
        else:
            return ["Hiçbir mağazada stokta bulunmuyor"]
        
    except Exception as e:
        print(f"Mağaza stok bilgisi çekme hatası: {e}")
        return None

if __name__ == "__main__":
    test_cases = [
        "M Turuncu",
        "Marlin 6 M Turuncu",
        "L Siyah"
    ]
    
    for test_case in test_cases:
        print(f"\n=== Testing: {test_case} ===")
        result = get_warehouse_stock(test_case)
        if result:
            print("Sonuç:")
            for item in result:
                print(f"  • {item}")
        else:
            print("Sonuç bulunamadı")
        print("-" * 50)