File size: 10,677 Bytes
58f6928
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import unicodedata
from typing import Any

from data.database import get_connection, initialize_database


def normalize_text(value: str) -> str:
    """
    Türkçe karakter ve büyük-küçük harf farklılıklarını azaltarak
    arama işlemlerini daha dayanıklı hâle getirir.

    Örnek:
        "KÖRLÜK" -> "korluk"
        "Suç ve Ceza" -> "suc ve ceza"
    """

    value = value.strip().casefold()

    replacements = {
        "ı": "i",
        "ğ": "g",
        "ü": "u",
        "ş": "s",
        "ö": "o",
        "ç": "c",
    }

    for source, target in replacements.items():
        value = value.replace(source, target)

    return "".join(
        character
        for character in unicodedata.normalize("NFKD", value)
        if not unicodedata.combining(character)
    )


def serialize_book(book: Any) -> dict[str, Any]:
    """SQLite kitap satırını JSON uyumlu sözlüğe dönüştürür."""

    return {
        "book_id": book["id"],
        "title": book["title"],
        "author": book["author"],
        "category": book["category"],
        "price": round(float(book["price"]), 2),
        "stock": int(book["stock"]),
        "available": int(book["stock"]) > 0,
    }


def search_books(
    query: str | None = None,
    author: str | None = None,
    category: str | None = None,
    in_stock_only: bool = False,
    limit: int = 10,
) -> dict[str, Any]:
    """
    Kitapları başlık, yazar veya kategoriye göre arar.

    Model, kitap bilgilerini kendisi üretmek yerine bu fonksiyondan
    dönen gerçek verileri kullanmalıdır.
    """

    initialize_database()

    if limit < 1:
        return {
            "success": False,
            "error": "limit değeri en az 1 olmalıdır.",
        }

    limit = min(limit, 20)

    normalized_query = normalize_text(query) if query else None
    normalized_author = normalize_text(author) if author else None
    normalized_category = normalize_text(category) if category else None

    with get_connection() as connection:
        rows = connection.execute(
            """
            SELECT
                id,
                title,
                author,
                category,
                price,
                stock
            FROM books
            ORDER BY title
            """
        ).fetchall()

    matched_books: list[dict[str, Any]] = []

    for row in rows:
        normalized_title_value = normalize_text(row["title"])
        normalized_author_value = normalize_text(row["author"])
        normalized_category_value = normalize_text(row["category"])

        if normalized_query:
            query_matches = (
                normalized_query in normalized_title_value
                or normalized_query in normalized_author_value
                or normalized_query in normalized_category_value
            )

            if not query_matches:
                continue

        if (
            normalized_author
            and normalized_author not in normalized_author_value
        ):
            continue

        if (
            normalized_category
            and normalized_category not in normalized_category_value
        ):
            continue

        if in_stock_only and row["stock"] <= 0:
            continue

        matched_books.append(serialize_book(row))

        if len(matched_books) >= limit:
            break

    return {
        "success": True,
        "count": len(matched_books),
        "filters": {
            "query": query,
            "author": author,
            "category": category,
            "in_stock_only": in_stock_only,
            "limit": limit,
        },
        "books": matched_books,
        "message": (
            f"{len(matched_books)} kitap bulundu."
            if matched_books
            else "Arama kriterlerine uygun kitap bulunamadı."
        ),
    }


def create_order(
    book_id: int,
    quantity: int,
    customer_name: str,
) -> dict[str, Any]:
    """
    Sipariş oluşturur ve kitap stoğunu düşürür.

    Sipariş kaydı ile stok güncellemesi aynı transaction içinde yapılır.
    Böylece işlemlerden biri başarısız olursa veritabanı yarım kalmaz.
    """

    initialize_database()

    customer_name = customer_name.strip()

    if not customer_name:
        return {
            "success": False,
            "error": "Müşteri adı boş bırakılamaz.",
        }

    if not isinstance(book_id, int) or isinstance(book_id, bool):
        return {
            "success": False,
            "error": "book_id tam sayı olmalıdır.",
        }

    if not isinstance(quantity, int) or isinstance(quantity, bool):
        return {
            "success": False,
            "error": "quantity tam sayı olmalıdır.",
        }

    if quantity < 1:
        return {
            "success": False,
            "error": "Sipariş miktarı en az 1 olmalıdır.",
        }

    connection = get_connection()

    try:
        # Aynı anda gelen iki siparişin aynı stoğu kullanmasını önlemek
        # için yazma kilidiyle transaction başlatılır.
        connection.execute("BEGIN IMMEDIATE")

        book = connection.execute(
            """
            SELECT
                id,
                title,
                author,
                category,
                price,
                stock
            FROM books
            WHERE id = ?
            """,
            (book_id,),
        ).fetchone()

        if book is None:
            connection.rollback()

            return {
                "success": False,
                "error": "Belirtilen kimliğe sahip kitap bulunamadı.",
                "book_id": book_id,
            }

        current_stock = int(book["stock"])

        if current_stock < quantity:
            connection.rollback()

            return {
                "success": False,
                "error": "Yeterli stok bulunmuyor.",
                "book_id": book_id,
                "title": book["title"],
                "requested_quantity": quantity,
                "available_stock": current_stock,
            }

        unit_price = round(float(book["price"]), 2)
        total_price = round(unit_price * quantity, 2)
        new_stock = current_stock - quantity

        cursor = connection.execute(
            """
            INSERT INTO orders (
                customer_name,
                book_id,
                quantity,
                unit_price,
                total_price,
                status
            )
            VALUES (?, ?, ?, ?, ?, ?)
            """,
            (
                customer_name,
                book_id,
                quantity,
                unit_price,
                total_price,
                "Hazırlanıyor",
            ),
        )

        order_id = cursor.lastrowid

        connection.execute(
            """
            UPDATE books
            SET stock = ?
            WHERE id = ?
            """,
            (
                new_stock,
                book_id,
            ),
        )

        connection.commit()

        return {
            "success": True,
            "message": "Sipariş başarıyla oluşturuldu.",
            "order": {
                "order_id": order_id,
                "customer_name": customer_name,
                "book_id": book_id,
                "title": book["title"],
                "author": book["author"],
                "quantity": quantity,
                "unit_price": unit_price,
                "total_price": total_price,
                "status": "Hazırlanıyor",
            },
            "stock_update": {
                "previous_stock": current_stock,
                "new_stock": new_stock,
            },
        }

    except Exception as error:
        connection.rollback()

        return {
            "success": False,
            "error": "Sipariş oluşturulurken veritabanı hatası oluştu.",
            "detail": str(error),
        }

    finally:
        connection.close()


def get_order_status(order_id: int) -> dict[str, Any]:
    """Sipariş numarasına göre sipariş bilgilerini getirir."""

    initialize_database()

    if not isinstance(order_id, int) or isinstance(order_id, bool):
        return {
            "success": False,
            "error": "order_id tam sayı olmalıdır.",
        }

    with get_connection() as connection:
        order = connection.execute(
            """
            SELECT
                orders.id AS order_id,
                orders.customer_name,
                orders.quantity,
                orders.unit_price,
                orders.total_price,
                orders.status,
                orders.created_at,
                books.id AS book_id,
                books.title,
                books.author
            FROM orders
            INNER JOIN books
                ON books.id = orders.book_id
            WHERE orders.id = ?
            """,
            (order_id,),
        ).fetchone()

    if order is None:
        return {
            "success": False,
            "error": "Sipariş bulunamadı.",
            "order_id": order_id,
        }

    return {
        "success": True,
        "order": {
            "order_id": order["order_id"],
            "customer_name": order["customer_name"],
            "book_id": order["book_id"],
            "title": order["title"],
            "author": order["author"],
            "quantity": order["quantity"],
            "unit_price": round(float(order["unit_price"]), 2),
            "total_price": round(float(order["total_price"]), 2),
            "status": order["status"],
            "created_at": order["created_at"],
        },
    }


TOOL_FUNCTIONS = {
    "search_books": search_books,
    "create_order": create_order,
    "get_order_status": get_order_status,
}


def execute_tool(
    tool_name: str,
    arguments: dict[str, Any],
) -> dict[str, Any]:
    """
    Model tarafından seçilen tool adını ilgili Python fonksiyonuna yönlendirir.
    """

    tool_function = TOOL_FUNCTIONS.get(tool_name)

    if tool_function is None:
        return {
            "success": False,
            "error": f"Desteklenmeyen tool: {tool_name}",
        }

    try:
        return tool_function(**arguments)

    except TypeError as error:
        return {
            "success": False,
            "error": "Tool parametreleri geçersiz veya eksik.",
            "detail": str(error),
        }

    except Exception as error:
        return {
            "success": False,
            "error": "Tool çalıştırılırken beklenmeyen hata oluştu.",
            "detail": str(error),
        }