# Stock Allocation System - Implementation Summary

## 📋 Genel Bakış

Apper Finance ve Apper Posmanager arasında stok dağıtım entegrasyonu için geliştirilen sistem.

### Senaryo Örneği
1. **Finance**: Tedarikçiden 5 kg limon alındı → fatura oluşturuldu
2. **Kullanıcı**: "Bu limonu 3 kg Şube A'ya, 2 kg Depo B'ye dağıt"
3. **Finance**: `stock_allocations` tablosuna 2 satır kaydedildi
4. **Entegrasyon**: Job sistemi ile Posmanager'a otomatik gönderim
5. **Posmanager**: Her hesap için `stock_transactions` oluşturuldu
6. **Raporlama**: "Şube A'daki limon maliyeti 45 TL/kg"

---

## 🗄️ Veritabanı

### Tablo: `stock_allocations`

```sql
- id
- tool_name (default: 'finance')
- current_team_id (FK: teams)
- user_id (FK: users)
- invoice_line_id (FK: invoice_lines)
- target_account_id (FK: integrations)
- allocated_quantity (decimal 10,2)
- unit_cost (decimal 10,2)
- total_cost (virtual: quantity * unit_cost)
- status (enum: planned, sent, failed, completed)
- sent_at (timestamp, nullable)
- external_ref (string, nullable) - Posmanager'daki ID
- error_message (text, nullable)
- timestamps
```

---

## 📁 Oluşturulan Dosyalar

### 1. Model
- **`app/Models/StockAllocation.php`**
  - İlişkiler: Team, User, InvoiceLine, Integration (targetAccount)
  - Scope'lar: planned, sent, failed, completed, forTeam
  - Helper metodlar: markAsSent, markAsCompleted, markAsFailed
  - Virtual attribute: total_cost

### 2. Controller
- **`app/Http/Controllers/StockAllocationController.php`**
  - `index()` - Liste ve istatistikler
  - `create()` - Yeni dağıtım formu
  - `store()` - Dağıtım kaydetme (validasyon + auto_send)
  - `show()` - Detay görüntüleme
  - `edit()` / `update()` - Düzenleme (sadece planned/failed)
  - `destroy()` - Silme (sadece planned/failed)
  - `sendToPosmanager()` - Tek kayıt gönderimi
  - `sendBulkToPosmanager()` - Toplu gönderim
  - `retryFailed()` - Başarısız gönderimi tekrarlama
  - `allocateFromInvoice()` - Fatura bazlı dağıtım

### 3. Service
- **`app/Services/PosmanagerService.php`**
  - `sendStockAllocation()` - Ana gönderim metodu
  - `checkStockStatus()` - Durum sorgulama
  - `sendBulkAllocations()` - Toplu gönderim
  - `getAccountStockSummary()` - Hesap stok özeti

### 4. Job
- **`app/Jobs/SendStockAllocationJob.php`**
  - Asenkron queue ile gönderim
  - 3 deneme hakkı (1dk, 5dk, 15dk backoff)
  - Başarısız olunca `failed()` metodu çalışır
  - Unique ID ile tekrarlı ekleme önlenir

### 5. Route
- **`routes/web.php`**
  - `stock-allocations.index`
  - `stock-allocations.create`
  - `stock-allocations.store`
  - `stock-allocations.show`
  - `stock-allocations.edit`
  - `stock-allocations.update`
  - `stock-allocations.destroy`
  - `stock-allocations.send-to-posmanager`
  - `stock-allocations.send-bulk-to-posmanager`
  - `stock-allocations.retry-failed`
  - `invoices.allocate-stock` (kısayol)

### 6. Config
- **`config/services.php`**
  ```php
  'posmanager' => [
      'url' => env('POSMANAGER_API_URL'),
      'api_key' => env('POSMANAGER_API_KEY'),
  ]
  ```

### 7. Service Provider
- **`app/Providers/AppServiceProvider.php`**
  - `PosmanagerService` singleton olarak register edildi

---

## 🔗 İlişkiler

### InvoiceLine Model
```php
// Eklenen ilişkiler
public function stockAllocations()
public function getTotalAllocatedQuantityAttribute()
public function getRemainingQuantityAttribute()
```

---

## 🚀 Kullanım

### 1. Manuel Dağıtım
```php
$allocation = StockAllocation::create([...]);
$posmanagerService->sendStockAllocation($allocation);
```

### 2. Job ile Asenkron
```php
SendStockAllocationJob::dispatch($allocation);
```

### 3. Toplu Gönderim
```php
$allocations = StockAllocation::planned()->get();
foreach ($allocations as $allocation) {
    SendStockAllocationJob::dispatch($allocation);
}
```

### 4. Başarısız Tekrar Deneme
```php
$allocation->update(['status' => 'planned', 'error_message' => null]);
SendStockAllocationJob::dispatch($allocation);
```

---

## 🔧 Kurulum Adımları

### 1. Environment Variables (.env)
```env
POSMANAGER_API_URL=https://posmanager.apper.com.tr
POSMANAGER_API_KEY=your-api-key-here
```

### 2. Migration Çalıştır
```bash
php artisan migrate
```

### 3. Queue Worker (Opsiyonel)
```bash
php artisan queue:work --tries=3
```

---

## 📊 API Payload (Finance → Posmanager)

```json
{
  "external_ref": "FINANCE-123",
  "source": "apper_finance",
  "source_id": 123,
  "account_id": "posmanager_account_123",
  "transaction_type": "incoming",
  "transaction_date": "2025-11-12 10:30:00",
  "product": {
    "code": "LMN001",
    "name": "Limon",
    "barcode": "8690123456789"
  },
  "quantity": 3.00,
  "unit_cost": 45.00,
  "total_cost": 135.00,
  "currency": "TRY",
  "invoice_ref": "FTR2025000123",
  "invoice_date": "2025-11-12",
  "metadata": {
    "team_id": 1,
    "user_id": 5,
    "invoice_line_id": 456
  }
}
```

---

## ✅ Özellikler

- ✅ CRUD işlemleri (Create, Read, Update, Delete)
- ✅ Durum yönetimi (planned, sent, failed, completed)
- ✅ Posmanager entegrasyonu
- ✅ Asenkron gönderim (Queue/Job)
- ✅ Retry mekanizması (3 deneme)
- ✅ Toplu gönderim
- ✅ Fatura bazlı dağıtım
- ✅ Activity ve Log kayıtları
- ✅ Team bazlı filtreleme
- ✅ Kalan miktar kontrolü
- ✅ API error handling

---

## 🎯 Sırada Ne Var?

1. **View Sayfaları** (Blade/Livewire)
   - index.blade.php
   - create.blade.php
   - show.blade.php
   - edit.blade.php
   - allocate-from-invoice.blade.php

2. **Test Yazma**
   - Unit tests
   - Feature tests
   - Integration tests

3. **Posmanager Tarafı**
   - API endpoint'leri
   - Stock transaction kayıt sistemi
   - Raporlama

---

## 📝 Notlar

- Tüm işlemler team bazlı izole edilmiştir
- Log kayıtları `Apper\LogManager` ile tutulur
- Activity kayıtları `RecordActivity` action'ı ile tutulur
- API timeout: 30 saniye
- Job timeout: 120 saniye
- Sadece `planned` ve `failed` durumlar düzenlenebilir/silinebilir

