File size: 7,121 Bytes
edf6940
 
 
 
 
 
 
 
8ba1576
edf6940
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ba1576
edf6940
 
 
 
 
 
 
 
 
 
 
8ba1576
edf6940
 
8ba1576
 
 
 
 
edf6940
 
8ba1576
 
 
 
 
 
 
edf6940
 
 
 
 
 
 
 
 
8ba1576
edf6940
 
 
8ba1576
edf6940
 
 
 
 
 
 
 
 
 
 
 
8ba1576
 
 
 
edf6940
 
8ba1576
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edf6940
8ba1576
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edf6940
8ba1576
 
edf6940
 
 
 
 
 
 
 
 
8ba1576
 
 
 
 
 
 
 
 
 
edf6940
8ba1576
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
"""Smart warehouse stock finder using GPT-5's intelligence"""

import requests
import re
import os
import json

def get_warehouse_stock_smart(user_message):
    """Let GPT-5 intelligently find ALL matching products in XML"""
    
    OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
    
    # Get XML data
    try:
        url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml-b2b-api-v2.php'
        response = requests.get(url, verify=False, timeout=7)
        xml_text = response.text
        print(f"DEBUG - XML fetched: {len(xml_text)} characters")
    except Exception as e:
        print(f"XML fetch error: {e}")
        return None
    
    # Extract just product blocks to reduce token usage
    product_pattern = r'<Product>(.*?)</Product>'
    all_products = re.findall(product_pattern, xml_text, re.DOTALL)
    
    # Create a simplified product list for GPT
    products_summary = []
    for i, product_block in enumerate(all_products):
        name_match = re.search(r'<ProductName><!\[CDATA\[(.*?)\]\]></ProductName>', product_block)
        variant_match = re.search(r'<ProductVariant><!\[CDATA\[(.*?)\]\]></ProductVariant>', product_block)
        
        if name_match:
            product_info = {
                "index": i,
                "name": name_match.group(1),
                "variant": variant_match.group(1) if variant_match else ""
            }
            products_summary.append(product_info)
    
    # Let GPT-5 find ALL matching products
    smart_prompt = f"""User is asking: "{user_message}"

Find ALL products that match this query from the list below.
If user asks about specific size (S, M, L, XL), return only that size.
If user asks generally (without size), return ALL variants of the product.

Products list:
{json.dumps(products_summary, ensure_ascii=False, indent=2)}

Return index numbers of ALL matching products as comma-separated list (e.g., "5,8,12,15").
If no products found, return: -1

Examples:
- "madone sl 6 var mı" -> Return ALL Madone SL 6 variants (all sizes)
- "madone sl 6 S beden" -> Return only S size variant
- "madone sl 6 gen 8" -> Return ALL variants of Madone SL 6 Gen 8"""

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {OPENAI_API_KEY}"
    }
    
    payload = {
        "model": "gpt-5-chat-latest",
        "messages": [
            {"role": "system", "content": "You are a product matcher. Find ALL matching products. Return only index numbers."},
            {"role": "user", "content": smart_prompt}
        ],
        "temperature": 0,
        "max_tokens": 100
    }
    
    try:
        response = requests.post(
            "https://api.openai.com/v1/chat/completions",
            headers=headers,
            json=payload,
            timeout=10
        )
        
        if response.status_code == 200:
            result = response.json()
            indices_str = result['choices'][0]['message']['content'].strip()
            
            if indices_str == "-1":
                return ["Ürün bulunamadı"]
            
            try:
                # Parse multiple indices
                indices = [int(idx.strip()) for idx in indices_str.split(',')]
                
                # Aggregate warehouse info from all matching products
                all_warehouses = {}
                product_names = []
                
                for idx in indices:
                    if 0 <= idx < len(all_products):
                        product_block = all_products[idx]
                        
                        # Get product name and variant
                        name_match = re.search(r'<ProductName><!\[CDATA\[(.*?)\]\]></ProductName>', product_block)
                        variant_match = re.search(r'<ProductVariant><!\[CDATA\[(.*?)\]\]></ProductVariant>', product_block)
                        
                        if name_match:
                            product_desc = name_match.group(1)
                            if variant_match and variant_match.group(1):
                                product_desc += f" ({variant_match.group(1)})"
                            product_names.append(product_desc)
                        
                        # Get warehouse stock
                        warehouse_regex = r'<Warehouse>.*?<Name><!\[CDATA\[(.*?)\]\]></Name>.*?<Stock>(.*?)</Stock>.*?</Warehouse>'
                        warehouses = re.findall(warehouse_regex, product_block, re.DOTALL)
                        
                        for wh_name, wh_stock in warehouses:
                            try:
                                stock = int(wh_stock.strip())
                                if stock > 0:
                                    # Format warehouse name
                                    display_name = format_warehouse_name(wh_name)
                                    
                                    if display_name not in all_warehouses:
                                        all_warehouses[display_name] = 0
                                    all_warehouses[display_name] += stock
                            except:
                                pass
                
                # Format result
                if product_names:
                    result = []
                    
                    # Show product variants found
                    if len(product_names) > 1:
                        result.append(f"Bulunan {len(product_names)} varyant:")
                        for name in product_names[:5]:  # Show first 5 variants
                            result.append(f"• {name}")
                        if len(product_names) > 5:
                            result.append(f"... ve {len(product_names) - 5} varyant daha")
                        result.append("")
                    
                    # Show aggregated warehouse stock
                    if all_warehouses:
                        result.append("Toplam stok durumu:")
                        for warehouse, total_stock in sorted(all_warehouses.items()):
                            result.append(f"{warehouse}: {total_stock} adet")
                    else:
                        result.append("Hiçbir mağazada stok yok")
                    
                    return result
                
            except (ValueError, IndexError) as e:
                print(f"DEBUG - Error parsing indices: {e}")
                return None
        else:
            print(f"GPT API error: {response.status_code}")
            return None
            
    except Exception as e:
        print(f"Error calling GPT: {e}")
        return None

def format_warehouse_name(wh_name):
    """Format warehouse name nicely"""
    if "CADDEBOSTAN" in wh_name:
        return "Caddebostan mağazası"
    elif "ORTAKÖY" in wh_name:
        return "Ortaköy mağazası"
    elif "ALSANCAK" in wh_name:
        return "İzmir Alsancak mağazası"
    elif "BAHCEKOY" in wh_name or "BAHÇEKÖY" in wh_name:
        return "Bahçeköy mağazası"
    else:
        return wh_name.replace("MAGAZA DEPO", "").strip()