# 🔧 حل مشكلة سندات الاستلام النقدية في كشف حساب المورد
# Fix Cash Receipt Vouchers Not Showing in Supplier Statement

## 📋 المشكلة (Problem)

**العربية:**
سندات استلام النقدية من الموردين لا تظهر في كشف حساب المورد.

**English:**
Cash receipt vouchers from suppliers are not showing in supplier account statements.

---

## 🔍 السبب (Root Cause)

**العربية:**
الكود لم يكن يجلب سندات الاستلام من الموردين (`CustomerPayment` مع `supplier_id`) في كشف حساب المورد.

كان النظام يجلب فقط:
1. ✅ المشتريات (Purchases)
2. ✅ سندات الصرف للمورد (SupplierPayment)
3. ❌ سندات الاستلام من المورد (CustomerPayment مع supplier_id)

**English:**
The code was not fetching receipt vouchers from suppliers (`CustomerPayment` with `supplier_id`) in supplier statements.

The system was only fetching:
1. ✅ Purchases
2. ✅ Supplier Payments (SupplierPayment)
3. ❌ Supplier Receipts (CustomerPayment with supplier_id)

---

## 💡 ملاحظة مهمة (Important Note)

**نموذج CustomerPayment:**
- عندما يحتوي على `customer_id` → سند استلام من عميل (Receipt from Customer)
- عندما يحتوي على `supplier_id` → سند استلام من مورد (Receipt from Supplier)

**CustomerPayment Model:**
- When it has `customer_id` → Receipt from Customer
- When it has `supplier_id` → Receipt from Supplier (for returns/refunds)

---

## ✅ الحلول المُطبقة (Applied Solutions)

### 1. تحديث StatementService.php

**الملف:** `app/Services/StatementService.php`

#### التعديلات:

**أ. إضافة سندات الاستلام السابقة للرصيد الافتتاحي:**
```php
// جلب سندات الاستلام من المورد (مرتجعات أو استردادات)
$previousReceipts = CustomerPayment::where('supplier_id', $supplier->id)
    ->where('status', 'confirmed')
    ->when($from, fn($q) => $q->where('created_at', '<', $from))
    ->sum('amount');

$opening = $supplierOpeningBalance + $previousPurchases - $previousPurchasesPaid 
           - $previousPayments + $previousReceipts;
```

**ب. جلب سندات الاستلام في الفترة الحالية:**
```php
// جلب سندات الاستلام من المورد (مرتجعات أو استردادات)
$receipts = CustomerPayment::where('supplier_id', $supplier->id)
    ->where('status', 'confirmed')
    ->when($from, fn($q) => $q->where('created_at', '>=', $from))
    ->where('created_at', '<=', $to)
    ->orderBy('created_at')
    ->get();
```

**ج. إضافة سندات الاستلام للتفاصيل:**
```php
// إضافة سندات الاستلام من المورد (مرتجعات/استردادات)
foreach ($receipts as $receipt) {
    $description = 'استلام من المورد';

    $details[] = [
        'type' => 'receipt',
        'date' => $receipt->created_at->format('Y-m-d'),
        'description' => $description,
        'amount' => $receipt->amount,
        'payment_method' => $receipt->payment_method,
        'balance' => $current + $receipt->amount,
        'receipt_number' => $receipt->receipt_number,
    ];
    $current += $receipt->amount;
}
```

**د. إضافة إجمالي الاستلامات للنتيجة:**
```php
return [
    // ... existing fields
    'total_receipts' => $receipts->sum('amount'),
    // ... other fields
];
```

---

### 2. تحديث صفحة عرض كشف حساب المورد

**الملف:** `resources/views/filament/pages/supplier-statement-report.blade.php`

**التعديل:** إضافة نوع جديد لعرض سندات الاستلام:
```blade
@elseif($detail['type'] === 'receipt')
    <!-- سندات الاستلام من المورد -->
    <tr class="border-b bg-green-50">
        <td class="px-4 py-3">{{ $detail['date'] }}</td>
        <td class="px-4 py-3 text-purple-600 font-semibold">{{ $detail['receipt_number'] ?? 'N/A' }}</td>
        <td class="px-4 py-3 font-semibold text-purple-600">{{ $detail['description'] }}</td>
        <td colspan="5"></td>
        <td class="px-4 py-3 text-right font-semibold text-purple-600">+{{ number_format($detail['amount'], 2) }}</td>
        <td class="px-4 py-3 text-right font-bold">{{ number_format($detail['balance'], 2) }}</td>
    </tr>
@endif
```

**إضافة إحصائية الاستلامات:**
```blade
<div>
    <p class="text-sm text-gray-600">إجمالي الاستلامات</p>
    <p class="text-lg font-bold text-purple-600">{{ number_format($this->statement_data['total_receipts'] ?? 0, 2) }} EGP</p>
</div>
```

---

### 3. تحديث تقرير PDF

**الملف:** `resources/views/reports/pdf/supplier-statement.blade.php`

**التعديلات:**
- إضافة نوع 'receipt' في جدول التفاصيل
- إضافة إجمالي الاستلامات في قسم الملخص

---

### 4. تحديث ملف Export

**الملف:** `app/Exports/SupplierStatementExport.php`

**التعديلات:**
- إضافة معالجة نوع 'receipt' عند بناء صفوف Excel
- إضافة إجمالي الاستلامات في الإحصائيات

---

### 5. تحديث تقرير كل الموردين

**الملف:** `app/Filament/Pages/AllSuppliersStatementReport.php`

**التعديلات:**

```php
// جلب سندات الاستلام من المورد (مرتجعات/استردادات)
$receipts_query = \App\Models\CustomerPayment::where('supplier_id', $supplier->id)
    ->where('status', 'confirmed');
if ($from_date) {
    $receipts_query->where('created_at', '>=', $from_date);
}
$receipts_query->where('created_at', '<=', $to_date);
$receipts = $receipts_query->get();

$total_receipts = $receipts->sum('amount');

// تحديث حساب الرصيد الختامي
$closing_balance = $opening_balance + $purchases->sum('remaining_amount') 
                   - $returns->sum('remaining_amount') - $total_receipts;
```

---

## 📊 النتائج المتوقعة (Expected Results)

### قبل التصحيح (Before Fix):
```
كشف حساب المورد:
- مشتريات #123: 5000 جنيه (دين على الشركة)
- سداد للمورد: -3000 جنيه
- [لا توجد سندات استلام معروضة]
- الرصيد: 2000 جنيه (نحن مدينون للمورد)

Supplier Statement:
- Purchase #123: 5000 EGP (we owe)
- Payment to Supplier: -3000 EGP
- [No receipt vouchers shown]
- Balance: 2000 EGP (we owe supplier)
```

### بعد التصحيح (After Fix):
```
كشف حساب المورد:
- مشتريات #123: 5000 جنيه (دين على الشركة)
- سداد للمورد: -3000 جنيه
- استلام من المورد: +500 جنيه ✅ (مرتجع/استرداد)
- الرصيد: 1500 جنيه (نحن مدينون للمورد)

Supplier Statement:
- Purchase #123: 5000 EGP (we owe)
- Payment to Supplier: -3000 EGP
- Receipt from Supplier: +500 EGP ✅ (return/refund)
- Balance: 1500 EGP (we owe supplier)
```

---

## 🔄 المنطق المحاسبي (Accounting Logic)

### رصيد المورد (Supplier Balance):
```
الرصيد الافتتاحي (Opening Balance)
+ المشتريات (Purchases) ← نحن مدينون
- المدفوعات (Payments) ← ندفع للمورد
- سندات الاستلام (Receipts) ← المورد يسترد/يعيد لنا
- مرتجعات المشتريات (Purchase Returns) ← نعيد بضاعة
= الرصيد الختامي (Closing Balance)
```

### متى نستخدم سند استلام من مورد؟
1. **مرتجع مشتريات نقدي** - أعدنا بضاعة واسترددنا نقدية
2. **استرداد دفعة زائدة** - دفعنا أكثر من المطلوب والمورد أعاد الفرق
3. **خصم نقدي** - المورد أعطانا خصم نقدي بعد الشراء

---

## ✅ التحقق من النجاح (Verify Success)

### 1. إنشاء سند استلام من مورد

```
من القائمة:
1. اذهب إلى: Customer Payments (سندات القبض)
2. إنشاء سند جديد
3. اختر مورد (لا تختر عميل)
4. أدخل المبلغ والتفاصيل
5. احفظ بحالة "confirmed"
```

### 2. التحقق من كشف الحساب

```
1. انتقل إلى: التقارير → كشف حساب مورد
2. اختر المورد الذي أنشأت له سند استلام
3. سترى:
   ✅ المشتريات (Purchases)
   ✅ سندات الصرف (Payments)
   ✅ سندات الاستلام (Receipts) - جديد!
   ✅ الرصيد صحيح ومحدّث
```

### 3. التحقق من قاعدة البيانات

```sql
-- سندات الاستلام من الموردين
SELECT 
    cp.receipt_number,
    s.name as supplier_name,
    cp.amount,
    cp.status,
    cp.created_at
FROM customer_payments cp
JOIN suppliers s ON cp.supplier_id = s.id
WHERE cp.supplier_id IS NOT NULL
  AND cp.status = 'confirmed'
ORDER BY cp.created_at DESC;
```

---

## 📝 الملفات المُعدَّلة (Modified Files)

1. ✅ [app/Services/StatementService.php](app/Services/StatementService.php)
2. ✅ [resources/views/filament/pages/supplier-statement-report.blade.php](resources/views/filament/pages/supplier-statement-report.blade.php)
3. ✅ [resources/views/reports/pdf/supplier-statement.blade.php](resources/views/reports/pdf/supplier-statement.blade.php)
4. ✅ [app/Exports/SupplierStatementExport.php](app/Exports/SupplierStatementExport.php)
5. ✅ [app/Filament/Pages/AllSuppliersStatementReport.php](app/Filament/Pages/AllSuppliersStatementReport.php)

---

## 📚 ملفات ذات صلة (Related Files)

- [PAYMENT_VOUCHERS_FIX.md](PAYMENT_VOUCHERS_FIX.md) - مشكلة سندات الصرف للعملاء
- [fix_payment_vouchers_status.php](fix_payment_vouchers_status.php) - تحديث حالة السندات

---

## 🎯 الخلاصة (Summary)

**العربية:**
✅ كشف حساب المورد يعرض الآن جميع المعاملات:
- المشتريات (Purchases)
- سندات الصرف للمورد (Payment to Supplier) - ندفع لهم
- سندات الاستلام من المورد (Receipt from Supplier) - يعيدون لنا
- مرتجعات المشتريات (Purchase Returns)

✅ الرصيد أصبح دقيقاً ويعكس جميع الحركات المالية

**English:**
✅ Supplier statement now shows all transactions:
- Purchases
- Payments to Supplier - we pay them
- Receipts from Supplier - they refund us
- Purchase Returns

✅ Balance is now accurate and reflects all financial movements

---

## 📅 التاريخ (Date)

**تاريخ التصحيح:** 22 فبراير 2026  
**Fix Date:** February 22, 2026

**الإصدار:** 1.0  
**Version:** 1.0

---

✅ **تم حل المشكلة بنجاح!**  
✅ **Issue Successfully Resolved!**
