# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## ⚠️ Kod yazmadan önce ARCHITECTURE.md'yi oku

[ARCHITECTURE.md](ARCHITECTURE.md) bu projenin **değişmez mimari anayasasıdır.** Hangi AI instance olursa olsun, hangi modül eklenirse eklensin — kod o dosyadaki kurallara göre yazılır. Katman atlatma, senkron IO, tenant izolasyon ihlali, response format sapması yasaktır.

---

## Proje: Flovy — AI Satış Asistanı SaaS

Flovy, işletmelerin web sitelerine tek satır kod ile ekleyebildiği, ziyaretçiyle konuşarak ürün öneren, sepet oluşturan, ödeme alan ve e-Fatura kesen bir conversational commerce ürünüdür. Bu repository, `flovy.tekyerden.co` adresinde çalışan **bağımsız SaaS backend**idir.

Panel.tekyerden.co'dan bağımsız çalışır. Oradan sadece iki şey taşınmıştır:
- Ürün modülü mantığı
- e-Fatura entegrasyon mantığı (Turkcell/iSIM360)

---

## En Kritik Rekabet Avantajı: Ziyaretçi Hafızası (Moat)

**Bizi diğer chatbot ürünlerinden ayıran tek şey budur.**

Tidio, Intercom, Crisp gibi rakipler her sohbeti sıfırdan başlatır. Flovy, aynı ziyaretçiyi tekrar tanır ve geçmişe dayalı kişiselleştirilmiş öneri sunar.

### Ziyaretçi Kimlik Tespiti (Çok Katmanlı)

Ziyaretçi sisteme girmeden tanınır — aşağıdaki sinyaller kombinasyonu ile:

| Sinyal | Güvenilirlik | Açıklama |
|---|---|---|
| E-posta (lead form / checkout) | ⭐⭐⭐⭐⭐ | En güçlü tanımlayıcı |
| Telefon | ⭐⭐⭐⭐⭐ | Formdan alındığında |
| Browser fingerprint | ⭐⭐⭐⭐ | Canvas + audio + font kombinasyonu |
| LocalStorage UUID | ⭐⭐⭐⭐ | Tarayıcı kapatılsa bile kalır |
| IP adresi | ⭐⭐ | Yardımcı sinyal, tek başına zayıf |
| UserAgent + ekran çözünürlüğü | ⭐⭐ | Fingerprint bileşeni |

Tüm sinyaller `flovy_visitors` tablosunda birleştirilir. E-posta/telefon eşleşmesi olunca anonim profil gerçek profile merge edilir.

### Ziyaretçi Profili Ne İçerir?

```
flovy_visitors:
  - visitor_uuid (kalıcı anonim ID)
  - email, phone (varsa)
  - fingerprint_hash
  - ip_address
  - total_sessions, total_messages
  - products_viewed[], products_purchased[]
  - last_intent (son niyet: katalog, fiyat, randevu...)
  - lifetime_value (TL)
  - preferred_language
  - device_type (mobile/desktop)
```

### Bu Veriyle Ne Yapıyoruz?

1. **Tekrar gelen ziyaretçi tanınır**: "Geçen hafta baktığın Collagen ürünü hâlâ stokta"
2. **Cross-session öneri**: İlk sohbette beden sorduysa, ikinci sohbette varyant seçimi hatırlanır
3. **Intent pattern**: 3 kez fiyat sormuş, hiç almamış → indirim kuponu teklif et
4. **Tenant analitik**: En çok terk eden adım, dönüşüm hunisi, ürün bazlı ilgi oranı
5. **Fine-tune verisi**: Türkçe conversational commerce dataseti — rakibin satın alamayacağı moat

### KVKK Uyumu

- İlk sohbette aydınlatma metni + onay checkbox
- Ziyaretçi "verimi sil" diyebilir → tüm PII anonimleştirilir
- 90 gün sonra otomatik PII silme (Celery job)
- Tenant izinli, şifreli loglama

---

## Stack

| Katman | Teknoloji |
|---|---|
| Backend API | **Python 3.12 + FastAPI** (async ASGI) |
| DB | **MySQL** (aynı sunucu, ayrı DB: `tekyerden_flovy`) |
| Vektör arama | **MySQL cosine** → ilerleyen fazda MySQL vec extension |
| Cache / Queue | **Redis** |
| Background jobs | **Celery + Redis broker** |
| Streaming köprüsü | **Node.js** (mevcut `/home/tekyerden/flovy-stream/`) |
| Panel frontend | **Next.js 14** (ilerleyen faz) — şimdilik API-first |
| Widget JS | Vanilla JS + minimal CSS (embed snippet, gzipli <30KB) |

---

## Ortam Değişkenleri (.env)

```env
# DB
DB_HOST=localhost
DB_PORT=3306
DB_NAME=tekyerden_flovy
DB_USER=tekyerden_flovyuser
DB_PASSWORD=r~HQ3~SjF[WaQU;b

# Redis
REDIS_URL=redis://127.0.0.1:6379/1

# AI
GEMINI_API_KEY=...
GEMMA_MODEL=gemini-flash-lite-latest
GEMMA_ENDPOINT=https://generativelanguage.googleapis.com/v1beta

# Streaming köprüsü
STREAM_SECRET=...
STREAM_HOST=127.0.0.1
STREAM_PORT=8090
FLOVY_STREAMING_ENABLED=true

# e-Fatura (Turkcell/iSIM360)
TURKCELL_API_KEY=...
TURKCELL_API_URL=...

# PayTR (global Flovy credentials — tenant başına override mümkün)
PAYTR_MERCHANT_ID=...
PAYTR_MERCHANT_KEY=...
PAYTR_MERCHANT_SALT=...

# JWT
JWT_SECRET=...
JWT_TTL_DAYS=30

# Uygulama
APP_ENV=production
APP_BASE_URL=https://flovy.tekyerden.co
```

---

## Proje Dizin Yapısı

```
flovy.tekyerden.co/
├── CLAUDE.md
├── docs/
│   ├── 00-OVERVIEW.md          ← Genel mimari ve faz planı
│   ├── 01-AUTH.md              ← Tenant auth + plan sistemi
│   ├── 02-PRODUCTS.md          ← Ürün yönetimi modülü
│   ├── 03-WIDGET.md            ← Chat widget + embed
│   ├── 04-RAG.md               ← Bilgi tabanı + embedding
│   ├── 05-ROUTING.md           ← 3 katmanlı intent router
│   ├── 06-TOOLS.md             ← Tool sistemi
│   ├── 07-EFATURA.md           ← e-Fatura otomasyonu
│   ├── 08-PAYMENT.md           ← PayTR entegrasyonu
│   ├── 09-VISITOR-MEMORY.md    ← Ziyaretçi hafızası (moat)
│   └── 10-DB-SCHEMA.md         ← Tüm tablo şemaları
├── app/
│   ├── main.py
│   ├── config.py
│   ├── database.py
│   ├── auth/
│   ├── routers/
│   │   ├── auth.py
│   │   ├── products.py
│   │   ├── widget.py
│   │   ├── chat.py
│   │   ├── knowledge.py
│   │   └── webhooks.py
│   ├── models/
│   ├── schemas/
│   ├── services/
│   │   ├── ai/
│   │   │   ├── flovy_service.py
│   │   │   ├── intent_router.py
│   │   │   ├── rule_matcher.py
│   │   │   ├── semantic_router.py
│   │   │   ├── gemma_client.py
│   │   │   ├── prompt_builder.py
│   │   │   └── response_parser.py
│   │   ├── rag/
│   │   │   ├── knowledge_retriever.py
│   │   │   ├── knowledge_indexer.py
│   │   │   ├── embedding_client.py
│   │   │   └── product_matcher.py
│   │   ├── tools/
│   │   │   ├── registry.py
│   │   │   ├── search_products.py
│   │   │   ├── add_to_cart.py
│   │   │   ├── create_pay_link.py
│   │   │   ├── collect_lead.py
│   │   │   └── escalate_to_human.py
│   │   ├── payment/
│   │   │   └── paytr_service.py
│   │   ├── efatura/
│   │   │   └── turkcell_service.py
│   │   ├── visitor/
│   │   │   ├── visitor_service.py     ← Ziyaretçi tanıma + profil
│   │   │   ├── fingerprint.py         ← Sinyal birleştirme
│   │   │   └── memory_builder.py      ← Geçmiş → prompt context
│   │   └── chat_service.py
│   ├── tasks/
│   │   ├── celery_app.py
│   │   ├── index_knowledge.py
│   │   ├── warm_anchors.py
│   │   └── anonymize_pii.py           ← 90 gün PII silme
│   └── utils/
│       ├── security.py
│       └── cosine.py
├── requirements.txt
├── .env.example
└── Procfile
```

---

## Common Commands

```bash
# Geliştirme
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Production
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000

# Celery worker
celery -A app.tasks.celery_app worker --loglevel=info

# DB migration
alembic upgrade head
alembic revision --autogenerate -m "description"

# Tests
pytest
pytest tests/ -v --cov=app

# Lint
ruff check app/
black app/
mypy app/
```

---

## Mimari Kurallar

- **Thin router**: İş mantığı service katmanında, router sadece parse + format.
- **Tenant izolasyonu zorunlu**: Her DB sorgusu `tenant_id` ile filtrelenir.
- **Visitor izolasyonu zorunlu**: `visitor_uuid` her zaman `tenant_id` ile birlikte sorgulanır — cross-tenant sızıntı yasak.
- **Para işleyen tool'larda onay**: `create_pay_link` onay olmadan tetiklenemez.
- **Async everywhere**: DB (SQLAlchemy async), HTTP (httpx), cache (aioredis).
- **Streaming Node.js'te**: FastAPI `stream_token` üretir, akışı Node.js yapar.
- **Background job = Celery**: Embedding, scraping, PII silme HTTP request içinde çalışmaz.
- **Visitor memory her sohbette yüklenir**: `MemoryBuilder` ilk mesaj gelmeden önce profili hazırlar ve prompt'a inject eder.

---

## Modüller ve Öncelik Sırası

| # | Modül | Öncelik | Bağımlılık |
|---|---|---|---|
| 1 | Auth + Tenant | 🔴 Kritik | — |
| 2 | Ürünler | 🔴 Kritik | Auth |
| 3 | Chat Widget + Session | 🔴 Kritik | Auth |
| 4 | Visitor Hafızası | 🔴 Kritik | Chat |
| 5 | RAG + Embedding | 🟠 Yüksek | Ürünler |
| 6 | AI Routing | 🟠 Yüksek | RAG |
| 7 | Tool Sistemi | 🟠 Yüksek | Routing |
| 8 | PayTR Ödeme | 🟠 Yüksek | Tools |
| 9 | e-Fatura | 🟡 Orta | Ödeme |
| 10 | Panel Frontend | 🟡 Orta | Tümü |

---

## İlgili Servisler

- `flovy-stream` Node.js: `/home/tekyerden/flovy-stream/` — PM2, port 8090
- MySQL: localhost:3306, DB: `tekyerden_flovy`
- Redis: localhost:6379, DB index 1
- Referans panel: `/home/tekyerden/public_html/panel.tekyerden.co/`
