tahamostafa07a4-cloud opened a new pull request, #1874:
URL: https://github.com/apache/cordova-android/pull/1874

   <!DOCTYPE html>
   <html lang="ar" dir="rtl">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>تطبيق إدارة المخزون والمبيعات والزبائن والموردين</title>
       <!-- تحميل Tailwind CSS -->
       <script src="https://cdn.tailwindcss.com";></script>
       <!-- خط Inter -->
       <link rel="stylesheet" 
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap";>
       <style>
           /* تطبيق خط Inter وضبط التنسيق العام */
           body {
               font-family: 'Inter', sans-serif;
               background-color: #f3f4f6;
           }
           .action-btn {
               @apply px-3 py-1 text-sm font-medium rounded-lg transition 
duration-150 ease-in-out shadow-md;
           }
           input[type="text"], input[type="number"], select {
               @apply w-full p-3 border border-gray-300 rounded-lg 
focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 
ease-in-out;
           }
           .summary-card {
               @apply bg-white p-5 rounded-xl shadow-lg border-r-8;
           }
       </style>
   </head>
   <body class="p-4 md:p-8">
   
       <div id="app" class="max-w-6xl mx-auto">
           <header class="mb-8 text-center">
               <h1 class="text-4xl font-extrabold text-indigo-700 mb-2">نظام 
محاسبة المخزون، الزبائن، والموردين</h1>
               <p class="text-gray-600">تتبع الأصناف، الأسعار، وإدارة ديون 
الزبائن والالتزامات للموردين.</p>
           </header>
   
           <!-- حالة تسجيل الدخول -->
           <div id="auth-status" class="bg-white p-4 rounded-xl shadow-lg mb-8 
text-sm text-gray-700 border-r-4 border-indigo-500">
               جار التحميل...
           </div>
   
           <!-- 1. ملخص مالي -->
           <section class="mb-8">
               <h2 class="text-2xl font-semibold text-gray-800 mb-4">الملخص 
المالي الإجمالي</h2>
               <div class="grid grid-cols-1 md:grid-cols-5 gap-6">
                   
                   <div class="summary-card border-indigo-500">
                       <p class="text-sm font-medium text-gray-500">رأس المال 
(قيمة التكلفة للمخزون)</p>
                       <p id="total-capital" class="text-3xl font-bold 
text-indigo-700 mt-1">0.00</p>
                   </div>
   
                   <div class="summary-card border-green-500">
                       <p class="text-sm font-medium text-gray-500">الربح 
المحتمل الإجمالي</p>
                       <p id="potential-profit" class="text-3xl font-bold 
text-green-700 mt-1">0.00</p>
                   </div>
   
                   <div class="summary-card border-yellow-500">
                       <p class="text-sm font-medium text-gray-500">القيمة 
الإجمالية للمخزون</p>
                       <p id="total-value" class="text-3xl font-bold 
text-yellow-700 mt-1">0.00</p>
                   </div>
   
                   <div class="summary-card border-red-500">
                       <p class="text-sm font-medium text-gray-500">إجمالي 
الديون المستحقة على الزبائن (أصول)</p>
                       <p id="total-debt" class="text-3xl font-bold 
text-red-600 mt-1">0.00</p>
                   </div>
   
                   <div class="summary-card border-purple-500">
                       <p class="text-sm font-medium text-gray-500">إجمالي 
المستحقات للموردين (التزامات)</p>
                       <p id="total-owed" class="text-3xl font-bold 
text-purple-600 mt-1">0.00</p>
                   </div>
   
               </div>
           </section>
   
           <!-- 2. إدارة الموردين -->
           <section class="bg-white p-6 rounded-xl shadow-lg mb-8">
               <h2 class="text-2xl font-semibold text-gray-800 mb-4 border-b 
pb-2">إدارة الموردين (المبالغ المستحقة عليهم)</h2>
               
               <form id="add-supplier-form" class="flex gap-4 items-end mb-6">
                   <div class="flex-grow">
                       <label for="supplier-name" class="block text-sm 
font-medium text-gray-700 mb-1">اسم المورد</label>
                       <input type="text" id="supplier-name" placeholder="مثال: 
شركة النور للاستيراد" required>
                   </div>
                   <button type="submit" class="bg-purple-600 
hover:bg-purple-700 text-white font-bold py-3 px-4 rounded-lg shadow-md 
transition duration-200">
                       إضافة مورد
                   </button>
               </form>
   
               <div class="overflow-x-auto">
                   <table class="min-w-full divide-y divide-gray-200">
                       <thead class="bg-gray-50">
                           <tr>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">اسم المورد</th>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">المستحق عليه 
(الالتزام)</th>
                               <th scope="col" class="px-3 py-3 text-center 
text-xs font-medium text-gray-500 uppercase tracking-wider">تسجيل دفعة 
للمورد</th>
                           </tr>
                       </thead>
                       <tbody id="suppliers-list" class="bg-white divide-y 
divide-gray-200">
                           <tr id="loading-suppliers"><td colspan="3" 
class="text-center py-4 text-gray-500">جار تحميل الموردين...</td></tr>
                       </tbody>
                   </table>
               </div>
               <div id="supplier-message" class="mt-4 text-sm text-center 
font-medium hidden"></div>
           </section>
   
           <!-- 3. تسجيل عملية شراء جديدة (فاتورة وارد) -->
           <section class="bg-white p-6 rounded-xl shadow-lg mb-8">
               <h2 class="text-2xl font-semibold text-gray-800 mb-4 border-b 
pb-2">تسجيل عملية شراء جديدة (إضافة مخزون)</h2>
               <form id="new-purchase-form" class="grid grid-cols-1 
md:grid-cols-6 gap-4 items-end">
                   <!-- اختيار المورد -->
                   <div class="md:col-span-2">
                       <label for="purchase-supplier-id" class="block text-sm 
font-medium text-gray-700 mb-1">المورد (مصدر البضاعة)</label>
                       <select id="purchase-supplier-id" required>
                           <option value="">-- اختر مورد أو شراء نقدي 
--</option>
                           <!-- يتم تعبئتها بواسطة JS -->
                       </select>
                   </div>
                   
                   <!-- اختيار الصنف -->
                   <div class="md:col-span-2">
                       <label for="purchase-item-id" class="block text-sm 
font-medium text-gray-700 mb-1">الصنف الذي تم شراؤه</label>
                       <select id="purchase-item-id" required>
                           <option value="">-- اختر صنفاً --</option>
                           <!-- يتم تعبئتها بواسطة JS -->
                       </select>
                   </div>
                   
                   <!-- الكمية -->
                   <div class="md:col-span-1">
                       <label for="purchase-quantity" class="block text-sm 
font-medium text-gray-700 mb-1">الكمية المشتراة</label>
                       <input type="number" id="purchase-quantity" min="1" 
value="1" required>
                   </div>
   
                   <!-- تفاصيل الدفع والآجل -->
                   <div class="md:col-span-1">
                       <p class="text-sm font-medium text-gray-700 mb-1">القيمة 
الإجمالية للشراء:</p>
                       <p id="purchase-total-value" class="text-lg font-bold 
text-blue-600">0.00</p>
                   </div>
                   <div class="md:col-span-2">
                       <label for="purchase-immediate-payment" class="block 
text-sm font-medium text-gray-700 mb-1">الدفع العاجل (المقدم للمورد)</label>
                       <input type="number" id="purchase-immediate-payment" 
step="0.01" min="0" value="0.00" required>
                   </div>
                   <div class="md:col-span-1">
                       <p class="text-sm font-medium text-gray-700 mb-1">المبلغ 
الآجل (المستحق للمورد):</p>
                       <p id="purchase-deferred-payment" class="text-lg 
font-bold text-purple-600">0.00</p>
                   </div>
                   
                   <!-- زر إتمام العملية -->
                   <div class="md:col-span-3">
                       <button type="submit" class="w-full bg-indigo-600 
hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-lg shadow-md 
transition duration-200">
                           إتمام عملية الشراء (إضافة للمخزون)
                       </button>
                   </div>
               </form>
               <div id="purchase-message" class="mt-4 text-sm text-center 
font-medium hidden"></div>
           </section>
   
   
           <!-- 4. إدارة الزبائن -->
           <section class="bg-white p-6 rounded-xl shadow-lg mb-8">
               <h2 class="text-2xl font-semibold text-gray-800 mb-4 border-b 
pb-2">إدارة الزبائن (الدفعات المستحقة لك)</h2>
               <form id="add-customer-form" class="flex gap-4 items-end mb-6">
                   <div class="flex-grow">
                       <label for="customer-name" class="block text-sm 
font-medium text-gray-700 mb-1">اسم الزبون</label>
                       <input type="text" id="customer-name" placeholder="مثال: 
أحمد محمد" required>
                   </div>
                   <button type="submit" class="bg-blue-600 hover:bg-blue-700 
text-white font-bold py-3 px-4 rounded-lg shadow-md transition duration-200">
                       إضافة زبون
                   </button>
               </form>
               <div class="overflow-x-auto">
                   <table class="min-w-full divide-y divide-gray-200">
                       <thead class="bg-gray-50">
                           <tr>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">اسم الزبون</th>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">الدين المستحق 
(الآجل)</th>
                               <th scope="col" class="px-3 py-3 text-center 
text-xs font-medium text-gray-500 uppercase tracking-wider">تسجيل دفعة</th>
                           </tr>
                       </thead>
                       <tbody id="customers-list" class="bg-white divide-y 
divide-gray-200">
                           <tr id="loading-customers"><td colspan="3" 
class="text-center py-4 text-gray-500">جار تحميل الزبائن...</td></tr>
                       </tbody>
                   </table>
               </div>
               <div id="customer-message" class="mt-4 text-sm text-center 
font-medium hidden"></div>
           </section>
   
           <!-- 5. تسجيل عملية بيع جديدة (فاتورة) -->
           <section class="bg-white p-6 rounded-xl shadow-lg mb-8">
               <h2 class="text-2xl font-semibold text-gray-800 mb-4 border-b 
pb-2">تسجيل عملية بيع جديدة (فاتورة مبيعات)</h2>
               <form id="new-sale-form" class="grid grid-cols-1 md:grid-cols-5 
gap-4 items-end">
                   <div class="md:col-span-2">
                       <label for="sale-item-id" class="block text-sm 
font-medium text-gray-700 mb-1">الصنف المباع</label>
                       <select id="sale-item-id" required>
                           <option value="">-- اختر صنفاً --</option>
                       </select>
                   </div>
                   <div>
                       <label for="sale-quantity" class="block text-sm 
font-medium text-gray-700 mb-1">الكمية</label>
                       <input type="number" id="sale-quantity" min="1" 
value="1" required>
                   </div>
                   <div class="md:col-span-2">
                       <label for="sale-customer-id" class="block text-sm 
font-medium text-gray-700 mb-1">الزبون</label>
                       <select id="sale-customer-id" required>
                           <option value="">-- بيع نقدي (لا يسجل دين) 
--</option>
                       </select>
                   </div>
                   <div class="md:col-span-1">
                       <p class="text-sm font-medium text-gray-700 mb-1">القيمة 
الإجمالية للبيع:</p>
                       <p id="sale-total-value" class="text-lg font-bold 
text-blue-600">0.00</p>
                   </div>
                   <div class="md:col-span-2">
                       <label for="sale-immediate-payment" class="block text-sm 
font-medium text-gray-700 mb-1">الدفع العاجل (المقدم)</label>
                       <input type="number" id="sale-immediate-payment" 
step="0.01" min="0" value="0.00" required>
                   </div>
                   <div class="md:col-span-1">
                       <p class="text-sm font-medium text-gray-700 mb-1">الدفع 
الآجل (الدين):</p>
                       <p id="sale-deferred-payment" class="text-lg font-bold 
text-red-600">0.00</p>
                   </div>
                   <div class="md:col-span-1">
                       <button type="submit" class="w-full bg-green-600 
hover:bg-green-700 text-white font-bold py-3 px-4 rounded-lg shadow-md 
transition duration-200">
                           إتمام عملية البيع
                       </button>
                   </div>
               </form>
               <div id="sale-message" class="mt-4 text-sm text-center 
font-medium hidden"></div>
           </section>
   
           <!-- 6. المخزون الحالي (فقط عرض) -->
           <section class="bg-white p-6 rounded-xl shadow-lg">
               <h2 class="text-2xl font-semibold text-gray-800 mb-4 border-b 
pb-2">تفاصيل المخزون الحالي (يتم التعديل عبر "عملية شراء")</h2>
               <div class="overflow-x-auto">
                   <table class="min-w-full divide-y divide-gray-200">
                       <thead class="bg-gray-50">
                           <tr>
                               <th scope="col" class="px-3 py-3 text-center 
text-xs font-medium text-gray-500 uppercase tracking-wider">صورة</th>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">الاسم</th>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">الرمز (SKU)</th>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">التكلفة</th>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">البيع</th>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">المخزون الحالي</th>
                               <th scope="col" class="px-3 py-3 text-right 
text-xs font-medium text-gray-500 uppercase tracking-wider">ربح الوحدة</th>
                           </tr>
                       </thead>
                       <tbody id="inventory-list" class="bg-white divide-y 
divide-gray-200">
                           <!-- سيتم تعبئة البيانات هنا بواسطة JavaScript -->
                       </tbody>
                   </table>
               </div>
               <p id="loading-indicator" class="text-center py-8 
text-gray-500">جار تحميل المخزون...</p>
               <p id="no-items-message" class="text-center py-8 text-gray-500 
hidden">لا يوجد أصناف في المخزون حالياً. أضف صنفاً جديداً للبدء.</p>
           </section>
   
           <!-- 7. إضافة صنف جديد (بقي في الأسفل) -->
           <section class="bg-white p-6 rounded-xl shadow-lg mb-8 mt-8">
               <h2 class="text-2xl font-semibold text-gray-800 mb-4 border-b 
pb-2">إضافة صنف جديد (يتم شراؤه لاحقاً عبر فاتورة الوارد)</h2>
               
               <form id="add-item-form" class="grid grid-cols-1 sm:grid-cols-2 
md:grid-cols-3 lg:grid-cols-6 gap-4 items-end">
                   <div class="lg:col-span-1 sm:col-span-2 md:col-span-1">
                       <label for="item-name" class="block text-sm font-medium 
text-gray-700 mb-1">اسم الصنف</label>
                       <input type="text" id="item-name" placeholder="اسم 
المنتج" required>
                   </div>
                   <div class="lg:col-span-1 sm:col-span-2 md:col-span-1">
                       <label for="item-sku" class="block text-sm font-medium 
text-gray-700 mb-1">رمز تسلسلي / QR (SKU)</label>
                       <input type="text" id="item-sku" placeholder="مثال: 
A-SKU-001" required>
                   </div>
                   <div class="lg:col-span-1">
                       <label for="item-cost" class="block text-sm font-medium 
text-gray-700 mb-1">سعر التكلفة (الأولي)</label>
                       <input type="number" id="item-cost" step="0.01" 
min="0.01" placeholder="مثال: 4.00" required>
                   </div>
                   <div class="lg:col-span-1">
                       <label for="item-price" class="block text-sm font-medium 
text-gray-700 mb-1">سعر البيع</label>
                       <input type="number" id="item-price" step="0.01" 
min="0.01" placeholder="مثال: 6.50" required>
                   </div>
                   <div class="lg:col-span-1">
                       <label for="initial-stock" class="block text-sm 
font-medium text-gray-700 mb-1">الكمية الأولية</label>
                       <input type="number" id="initial-stock" min="0" 
value="0" required>
                   </div>
                   <div class="lg:col-span-1">
                       <label for="item-image-url" class="block text-sm 
font-medium text-gray-700 mb-1">رابط صورة المنتج (URL)</label>
                       <input type="text" id="item-image-url" placeholder="رابط 
مباشر للصورة" value="https://placehold.co/40x40/4f46e5/ffffff?text=P"; required>
                   </div>
                   
                   <div class="lg:col-span-6 text-center mt-2">
                       <button type="submit" class="w-1/2 bg-indigo-600 
hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-lg shadow-md 
transition duration-200">
                           إضافة صنف
                       </button>
                   </div>
               </form>
           </section>
   
       </div>
   
       <!-- Firebase Imports and Setup -->
       <script type="module">
           import { initializeApp } from 
"https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";;
           import { getAuth, signInAnonymously, signInWithCustomToken, 
onAuthStateChanged } from 
"https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";;
           import { getFirestore, doc, addDoc, updateDoc, onSnapshot, 
collection, increment, serverTimestamp, setLogLevel, getDoc } from 
"https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";;
   
           setLogLevel('debug');
   
           // جلب المتغيرات العامة
           const appId = typeof __app_id !== 'undefined' ? __app_id : 
'default-app-id';
           const firebaseConfig = typeof __firebase_config !== 'undefined' ? 
JSON.parse(__firebase_config) : null;
           const initialAuthToken = typeof __initial_auth_token !== 'undefined' 
? __initial_auth_token : null;
           
           if (!firebaseConfig) {
               document.getElementById('auth-status').innerHTML = '<span 
class="text-red-600">خطأ: لم يتم العثور على إعدادات Firebase.</span>';
               console.error("Firebase config is missing.");
               // يجب أن تضمن بيئة Android Studio أو Cordova توفير هذه 
المتغيرات.
               return; 
           }
   
           const app = initializeApp(firebaseConfig);
           const db = getFirestore(app);
           const auth = getAuth(app);
   
           let userId = null;
           let isAuthReady = false;
           let inventoryItems = []; 
           let customersList = []; 
           let suppliersList = []; // قائمة الموردين الجديدة
   
           // المسارات الثابتة للمجموعات العامة
           const inventoryCollectionPath = 
`/artifacts/${appId}/public/data/inventory`;
           const customersCollectionPath = 
`/artifacts/${appId}/public/data/customers`;
           const suppliersCollectionPath = 
`/artifacts/${appId}/public/data/suppliers`; // مسار جديد للموردين
           const salesCollectionPath = `/artifacts/${appId}/public/data/sales`;
           const purchasesCollectionPath = 
`/artifacts/${appId}/public/data/purchases`; // مسار جديد للمشتريات
   
   
           // 1. مصادقة المستخدم
           async function authenticateUser() {
               try {
                   if (initialAuthToken) {
                       await signInWithCustomToken(auth, initialAuthToken);
                   } else {
                       await signInAnonymously(auth);
                   }
               } catch (error) {
                   console.error("Authentication Error:", error);
               }
           }
   
           // 2. معالج حالة المصادقة
           onAuthStateChanged(auth, (user) => {
               if (user) {
                   userId = user.uid;
                   isAuthReady = true;
                   document.getElementById('auth-status').innerHTML = `
                       <p class="font-bold">مسجل الدخول بنجاح.</p>
                       <p>معرف المستخدم: <span class="text-indigo-600 
font-mono">${userId}</span></p>
                   `;
                   // بدء مراقبة جميع البيانات المطلوبة
                   setupInventoryListener();
                   setupCustomersListener();
                   setupSuppliersListener(); // بدء مراقبة الموردين
               } else {
                   userId = null;
                   isAuthReady = false;
                   document.getElementById('auth-status').innerHTML = '<span 
class="text-red-600">لم يتم تسجيل الدخول. محاولة تسجيل الدخول...</span>';
                   authenticateUser();
               }
           });
   
   
           // 3. مراقبة المخزون في الوقت الفعلي
           function setupInventoryListener() {
               if (!isAuthReady || !userId) return; 
               
               onSnapshot(collection(db, inventoryCollectionPath), (snapshot) 
=> {
                   inventoryItems = [];
                   snapshot.forEach(doc => {
                       inventoryItems.push({ id: doc.id, ...doc.data() });
                   });
   
                   calculateFinancialSummary(inventoryItems, customersList, 
suppliersList);
                   renderInventory(inventoryItems);
                   populateItemSelect(inventoryItems); 
                   
document.getElementById('loading-indicator').classList.add('hidden');
               }, (error) => {
                   console.error("Error listening to inventory:", error);
                   showMessage(`خطأ في جلب بيانات المخزون: ${error.message}`, 
'error', 'auth-status');
               });
           }
           
           // 4. مراقبة الزبائن في الوقت الفعلي
           function setupCustomersListener() {
               if (!isAuthReady || !userId) return; 
   
               onSnapshot(collection(db, customersCollectionPath), (snapshot) 
=> {
                   customersList = [];
                   snapshot.forEach(doc => {
                       customersList.push({ id: doc.id, ...doc.data() });
                   });
                   
                   renderCustomers(customersList);
                   populateCustomerSelect(customersList); 
                   calculateFinancialSummary(inventoryItems, customersList, 
suppliersList);
               }, (error) => {
                   console.error("Error listening to customers:", error);
                   showMessage(`خطأ في جلب بيانات الزبائن: ${error.message}`, 
'error', 'auth-status');
               });
           }
           
           // 5. مراقبة الموردين في الوقت الفعلي (جديد)
           function setupSuppliersListener() {
               if (!isAuthReady || !userId) return; 
   
               onSnapshot(collection(db, suppliersCollectionPath), (snapshot) 
=> {
                   suppliersList = [];
                   snapshot.forEach(doc => {
                       suppliersList.push({ id: doc.id, ...doc.data() });
                   });
                   
                   renderSuppliers(suppliersList);
                   populateSupplierSelect(suppliersList); // تحديث قائمة 
الموردين
                   calculateFinancialSummary(inventoryItems, customersList, 
suppliersList);
               }, (error) => {
                   console.error("Error listening to suppliers:", error);
                   showMessage(`خطأ في جلب بيانات الموردين: ${error.message}`, 
'error', 'auth-status');
               });
           }
   
   
           // 6. حساب الملخص المالي الإجمالي (محدث)
           function calculateFinancialSummary(items, customers, suppliers) {
               let totalCapital = 0;
               let totalValue = 0;
               let totalDebt = 0; // الأصول (زبائن)
               let totalOwed = 0; // الالتزامات (موردين)
   
               items.forEach(item => {
                   const stock = item.stock || 0;
                   const cost = item.costPrice || 0;
                   const price = item.price || 0;
                   totalCapital += stock * cost;
                   totalValue += stock * price;
               });
               
               customers.forEach(customer => {
                   totalDebt += customer.totalDebt || 0;
               });
               
               suppliers.forEach(supplier => {
                   totalOwed += supplier.totalOwed || 0;
               });
   
   
               const potentialProfit = totalValue - totalCapital;
   
               // تحديث واجهة المستخدم
               document.getElementById('total-capital').textContent = 
totalCapital.toFixed(2);
               document.getElementById('total-value').textContent = 
totalValue.toFixed(2);
               document.getElementById('potential-profit').textContent = 
potentialProfit.toFixed(2);
               document.getElementById('total-debt').textContent = 
totalDebt.toFixed(2);
               document.getElementById('total-owed').textContent = 
totalOwed.toFixed(2);
           }
   
           // 7. عرض قائمة الموردين (جديد)
           function renderSuppliers(suppliers) {
               const supplierBody = document.getElementById('suppliers-list');
               supplierBody.innerHTML = '';
               
               if (suppliers.length === 0) {
                   supplierBody.innerHTML = '<tr><td colspan="3" 
class="text-center py-4 text-gray-500">لا يوجد موردون مسجلون حالياً.</td></tr>';
                   return;
               }
   
               suppliers.sort((a, b) => (a.name || '').localeCompare(b.name || 
''));
   
               suppliers.forEach(supplier => {
                   const row = document.createElement('tr');
                   row.className = 'hover:bg-gray-50 transition duration-150';
                   const owed = (supplier.totalOwed || 0).toFixed(2);
                   const owedColor = owed > 0 ? 'text-red-600 font-bold' : 
'text-green-600';
   
                   row.innerHTML = `
                       <td class="px-3 py-3 whitespace-nowrap text-sm 
font-medium text-gray-900">${supplier.name || 'مورد غير معروف'}</td>
                       <td class="px-3 py-3 whitespace-nowrap text-sm 
${owedColor}">${owed}</td>
                       <td class="px-3 py-3 whitespace-nowrap text-center 
text-sm font-medium">
                           ${owed > 0 ? 
                               `<form class="flex gap-2 justify-center 
supplier-payment-form" data-supplier-id="${supplier.id}">
                                   <input type="number" step="0.01" min="0.01" 
placeholder="مقدار الدفعة" required class="w-32 p-1 text-center text-sm 
border-gray-300 rounded-lg payment-input">
                                   <button type="submit" class="action-btn 
bg-purple-500 hover:bg-purple-600 text-white">تسجيل دفع</button>
                               </form>`
                               : '<span class="text-gray-400">لا يوجد 
مستحقات</span>'
                           }
                       </td>
                   `;
                   supplierBody.appendChild(row);
               });
               
               // إضافة معالج لنموذج الدفع للمورد
               
supplierBody.querySelectorAll('.supplier-payment-form').forEach(form => {
                   form.removeEventListener('submit', handleSupplierPayment);
                   form.addEventListener('submit', handleSupplierPayment);
               });
           }
           
           // 8. معالج نموذج إضافة مورد (جديد)
           
document.getElementById('add-supplier-form').addEventListener('submit', async 
(event) => {
               event.preventDefault();
               if (!isAuthReady || !userId) {
                   showMessage("الرجاء انتظار تسجيل الدخول أولاً.", 'error', 
'supplier-message');
                   return;
               }
               const name = 
document.getElementById('supplier-name').value.trim();
               if (!name) return;
   
               try {
                   await addDoc(collection(db, suppliersCollectionPath), {
                       name: name,
                       totalOwed: 0, // المبلغ الإجمالي المستحق للمورد
                       createdAt: serverTimestamp(),
                       createdBy: userId
                   });
                   document.getElementById('add-supplier-form').reset();
                   showMessage("تم إضافة المورد بنجاح!", 'success', 
'supplier-message');
               } catch (error) {
                   console.error("Error adding supplier:", error);
                   showMessage(`خطأ في إضافة المورد: ${error.message}`, 
'error', 'supplier-message');
               }
           });
   
           // 9. معالج تسجيل دفعة للمورد (جديد)
           async function handleSupplierPayment(event) {
               event.preventDefault();
               const supplierId = event.target.dataset.supplierId;
               const paymentInput = 
event.target.querySelector('.payment-input');
               const paymentAmount = parseFloat(paymentInput.value);
   
               if (isNaN(paymentAmount) || paymentAmount <= 0) {
                   showMessage("الرجاء إدخال مبلغ دفع صحيح.", 'error', 
'supplier-message');
                   return;
               }
   
               try {
                   const supplierRef = doc(db, suppliersCollectionPath, 
supplierId);
                   const supplierDoc = await getDoc(supplierRef);
                   const currentOwed = supplierDoc.data().totalOwed || 0;
                   
                   // التأكد من أن الدفعة لا تتجاوز المستحق
                   const actualPayment = Math.min(paymentAmount, currentOwed);
                   
                   await updateDoc(supplierRef, {
                       totalOwed: increment(-actualPayment),
                       lastPayment: serverTimestamp()
                   });
   
                   paymentInput.value = ''; 
                   showMessage(`تم تسجيل دفعة بقيمة ${actualPayment.toFixed(2)} 
للمورد بنجاح!`, 'success', 'supplier-message');
   
               } catch (error) {
                   console.error("Error processing supplier payment:", error);
                   showMessage(`خطأ في تسجيل الدفعة: ${error.message}`, 
'error', 'supplier-message');
               }
           }
           
           // 10. تعبئة قائمة الموردين للبيع (جديد)
           function populateSupplierSelect(suppliers) {
               const select = document.getElementById('purchase-supplier-id');
               select.innerHTML = '<option value="">-- شراء نقدي (لا يسجل 
التزام) --</option>';
               suppliers.forEach(supplier => {
                   const option = document.createElement('option');
                   option.value = supplier.id;
                   option.textContent = supplier.name;
                   select.appendChild(option);
               });
           }
           
           // 11. تحديث قيمة الشراء الإجمالية والدفع الآجل (جديد)
           function updatePurchaseValue() {
               const itemId = document.getElementById('purchase-item-id').value;
               const quantity = 
parseInt(document.getElementById('purchase-quantity').value, 10) || 0;
               const immediatePayment = 
parseFloat(document.getElementById('purchase-immediate-payment').value) || 0;
   
               const selectedItem = inventoryItems.find(item => item.id === 
itemId);
               
               let totalValue = 0;
               let deferredPayment = 0;
   
               if (selectedItem) {
                   totalValue = selectedItem.costPrice * quantity; // يتم 
استخدام سعر التكلفة هنا
                   deferredPayment = Math.max(0, totalValue - immediatePayment);
               }
   
               document.getElementById('purchase-total-value').textContent = 
totalValue.toFixed(2);
               document.getElementById('purchase-deferred-payment').textContent 
= deferredPayment.toFixed(2);
   
               // تحديث حقل الدفع الآجل عند تغيير الدفع العاجل
               
document.getElementById('purchase-immediate-payment').removeEventListener('input',
 updateDeferredPurchasePayment);
               
document.getElementById('purchase-immediate-payment').addEventListener('input', 
updateDeferredPurchasePayment);
           }
           
           function updateDeferredPurchasePayment() {
               updatePurchaseValue(); // ببساطة إعادة تشغيل الدالة الرئيسية
           }
   
           // 12. معالج نموذج تسجيل عملية الشراء الجديدة (جديد)
           
document.getElementById('new-purchase-form').addEventListener('submit', async 
(event) => {
               event.preventDefault();
               if (!isAuthReady || !userId) {
                   showMessage("الرجاء انتظار تسجيل الدخول أولاً.", 'error', 
'purchase-message');
                   return;
               }
   
               const itemId = document.getElementById('purchase-item-id').value;
               const supplierId = 
document.getElementById('purchase-supplier-id').value || null; 
               const quantity = 
parseInt(document.getElementById('purchase-quantity').value, 10);
               const immediatePayment = 
parseFloat(document.getElementById('purchase-immediate-payment').value);
               
               const selectedItem = inventoryItems.find(item => item.id === 
itemId);
   
               if (!selectedItem) {
                   showMessage("الرجاء اختيار صنف صحيح.", 'error', 
'purchase-message');
                   return;
               }
   
               const totalPurchaseValue = selectedItem.costPrice * quantity;
               const deferredPayment = Math.max(0, totalPurchaseValue - 
immediatePayment);
               
               if (!supplierId && totalPurchaseValue > immediatePayment) {
                    showMessage("في حالة الشراء النقدي، يجب أن يكون الدفع 
العاجل مساوياً للقيمة الإجمالية للشراء.", 'error', 'purchase-message');
                    return;
               }
   
               let supplierName = supplierId ? suppliersList.find(s => s.id === 
supplierId)?.name : 'شراء نقدي';
   
   
               try {
                   // 1. تحديث المخزون (زيادة الكمية)
                   const itemRef = doc(db, inventoryCollectionPath, itemId);
                   await updateDoc(itemRef, {
                       stock: increment(quantity),
                       lastUpdated: serverTimestamp()
                   });
   
                   // 2. تسجيل العملية في جدول المشتريات
                   await addDoc(collection(db, purchasesCollectionPath), {
                       itemId: itemId,
                       itemName: selectedItem.name,
                       supplierId: supplierId,
                       supplierName: supplierName,
                       quantity: quantity,
                       costPricePerUnit: selectedItem.costPrice,
                       totalPurchaseValue: totalPurchaseValue,
                       immediatePayment: immediatePayment, // الدفعة العاجلة
                       deferredPayment: deferredPayment, // الدفعة الآجلة 
(المستحق)
                       timestamp: serverTimestamp()
                   });
                   
                   // 3. تحديث التزام المورد (إذا كان آجل)
                   if (deferredPayment > 0 && supplierId) {
                       const supplierRef = doc(db, suppliersCollectionPath, 
supplierId);
                       await updateDoc(supplierRef, {
                           totalOwed: increment(deferredPayment)
                       });
                   }
                   
                   document.getElementById('new-purchase-form').reset();
                   updatePurchaseValue(); 
                   showMessage(`تم تسجيل عملية شراء ناجحة. المبلغ المستحق 
للمورد: ${deferredPayment.toFixed(2)}`, 'success', 'purchase-message');
   
               } catch (error) {
                   console.error("Error processing new purchase:", error);
                   showMessage(`خطأ في إتمام عملية الشراء: ${error.message}`, 
'error', 'purchase-message');
               }
           });
           
           
           // 13. عرض قائمة الزبائن (Rendering) (تم نقله)
           function renderCustomers(customers) {
               const customerBody = document.getElementById('customers-list');
               customerBody.innerHTML = '';
               
               if (customers.length === 0) {
                   customerBody.innerHTML = '<tr><td colspan="3" 
class="text-center py-4 text-gray-500">لا يوجد زبائن مسجلين حالياً.</td></tr>';
                   return;
               }
   
               customers.sort((a, b) => (a.name || '').localeCompare(b.name || 
''));
   
               customers.forEach(customer => {
                   const row = document.createElement('tr');
                   row.className = 'hover:bg-gray-50 transition duration-150';
                   const debt = (customer.totalDebt || 0).toFixed(2);
                   const debtColor = debt > 0 ? 'text-red-600 font-bold' : 
'text-green-600';
   
                   row.innerHTML = `
                       <td class="px-3 py-3 whitespace-nowrap text-sm 
font-medium text-gray-900">${customer.name || 'زبون غير معروف'}</td>
                       <td class="px-3 py-3 whitespace-nowrap text-sm 
${debtColor}">${debt}</td>
                       <td class="px-3 py-3 whitespace-nowrap text-center 
text-sm font-medium">
                           ${debt > 0 ? 
                               `<form class="flex gap-2 justify-center 
customer-payment-form" data-customer-id="${customer.id}">
                                   <input type="number" step="0.01" min="0.01" 
placeholder="مقدار الدفعة" required class="w-32 p-1 text-center text-sm 
border-gray-300 rounded-lg payment-input">
                                   <button type="submit" class="action-btn 
bg-yellow-500 hover:bg-yellow-600 text-white">تسجيل دفع</button>
                               </form>`
                               : '<span class="text-gray-400">لا يوجد 
دين</span>'
                           }
                       </td>
                   `;
                   customerBody.appendChild(row);
               });
               
               // إضافة معالج لنموذج الدفع
               
customerBody.querySelectorAll('.customer-payment-form').forEach(form => {
                   form.removeEventListener('submit', handleCustomerPayment);
                   form.addEventListener('submit', handleCustomerPayment);
               });
           }
           
           // 14. معالج نموذج إضافة زبون
           
document.getElementById('add-customer-form').addEventListener('submit', async 
(event) => {
               event.preventDefault();
               if (!isAuthReady || !userId) {
                   showMessage("الرجاء انتظار تسجيل الدخول أولاً.", 'error', 
'customer-message');
                   return;
               }
               const name = 
document.getElementById('customer-name').value.trim();
               if (!name) return;
   
               try {
                   await addDoc(collection(db, customersCollectionPath), {
                       name: name,
                       totalDebt: 0,
                       createdAt: serverTimestamp(),
                       createdBy: userId
                   });
                   document.getElementById('add-customer-form').reset();
                   showMessage("تم إضافة الزبون بنجاح!", 'success', 
'customer-message');
               } catch (error) {
                   console.error("Error adding customer:", error);
                   showMessage(`خطأ في إضافة الزبون: ${error.message}`, 
'error', 'customer-message');
               }
           });
   
           // 15. معالج تسجيل دفعة من زبون
           async function handleCustomerPayment(event) {
               event.preventDefault();
               const customerId = event.target.dataset.customerId;
               const paymentInput = 
event.target.querySelector('.payment-input');
               const paymentAmount = parseFloat(paymentInput.value);
   
               if (isNaN(paymentAmount) || paymentAmount <= 0) {
                   showMessage("الرجاء إدخال مبلغ دفع صحيح.", 'error', 
'customer-message');
                   return;
               }
   
               try {
                   const customerRef = doc(db, customersCollectionPath, 
customerId);
                   const customerDoc = await getDoc(customerRef);
                   const currentDebt = customerDoc.data().totalDebt || 0;
                   
                   const actualPayment = Math.min(paymentAmount, currentDebt);
                   
                   await updateDoc(customerRef, {
                       totalDebt: increment(-actualPayment),
                       lastPayment: serverTimestamp()
                   });
   
                   paymentInput.value = ''; 
                   showMessage(`تم تسجيل دفعة بقيمة ${actualPayment.toFixed(2)} 
للزبون بنجاح!`, 'success', 'customer-message');
   
               } catch (error) {
                   console.error("Error processing payment:", error);
                   showMessage(`خطأ في تسجيل الدفعة: ${error.message}`, 
'error', 'customer-message');
               }
           }
           
           // 16. تعبئة قائمة الأصناف للبيع والشراء
           function populateItemSelect(items) {
               const saleSelect = document.getElementById('sale-item-id');
               const purchaseSelect = 
document.getElementById('purchase-item-id');
   
               saleSelect.innerHTML = '<option value="">-- اختر صنفاً 
--</option>';
               purchaseSelect.innerHTML = '<option value="">-- اختر صنفاً 
--</option>';
               
               items.forEach(item => {
                   const saleOption = document.createElement('option');
                   saleOption.value = item.id;
                   saleOption.textContent = `${item.name} (بيع: 
${item.price.toFixed(2)}, مخزون: ${item.stock})`;
                   saleSelect.appendChild(saleOption);
                   
                   const purchaseOption = document.createElement('option');
                   purchaseOption.value = item.id;
                   purchaseOption.textContent = `${item.name} (تكلفة: 
${item.costPrice.toFixed(2)}, مخزون: ${item.stock})`;
                   purchaseSelect.appendChild(purchaseOption);
               });
               
               // إضافة معالجات تحديث القيمة لنموذج البيع والشراء
               saleSelect.addEventListener('change', updateSaleValue);
               
document.getElementById('sale-quantity').addEventListener('input', 
updateSaleValue);
               
document.getElementById('sale-immediate-payment').addEventListener('input', 
updateSaleValue);
   
               purchaseSelect.addEventListener('change', updatePurchaseValue);
               
document.getElementById('purchase-quantity').addEventListener('input', 
updatePurchaseValue);
               
document.getElementById('purchase-immediate-payment').addEventListener('input', 
updatePurchaseValue);
           }
   
           // 17. عرض قائمة المخزون (Rendering) - الآن فقط للعرض
           function renderInventory(items) {
               const inventoryBody = document.getElementById('inventory-list');
               inventoryBody.innerHTML = '';
               
               if (items.length === 0) {
                   
document.getElementById('no-items-message').classList.remove('hidden');
                   return;
               }
               
document.getElementById('no-items-message').classList.add('hidden');
   
               items.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
   
               items.forEach(item => {
                   const row = document.createElement('tr');
                   row.className = 'hover:bg-gray-50 transition duration-150';
                   
                   const stock = typeof item.stock === 'number' ? 
Math.floor(item.stock) : 0;
                   const cost = item.costPrice || 0;
                   const price = item.price || 0;
                   const profitPerUnit = (price - cost).toFixed(2);
                   
                   const stockColor = stock <= 5 && stock > 0 ? 'bg-yellow-100 
text-yellow-800 p-1 rounded' : (stock <= 0 ? 'bg-red-100 text-red-800 p-1 
rounded' : 'text-green-600');
                   
                   const imageUrl = item.imageUrl || 
`https://placehold.co/40x40/cccccc/666666?text=P`;
   
                   row.innerHTML = `
                       <td class="px-3 py-3 whitespace-nowrap text-center 
text-sm">
                           <img src="${imageUrl}" alt="${item.name}" 
class="h-10 w-10 object-cover rounded-md mx-auto" onerror="this.onerror=null; 
this.src='https://placehold.co/40x40/cccccc/666666?text=N/A';" />
                       </td>
                       <td class="px-3 py-3 whitespace-nowrap text-sm 
font-medium text-gray-900">${item.name || 'صنف غير معروف'}</td>
                       <td class="px-3 py-3 whitespace-nowrap text-sm 
text-gray-700 font-mono">${item.sku || 'N/A'}</td>
   
                       <td class="px-3 py-3 whitespace-nowrap text-sm 
text-gray-500">${cost.toFixed(2)}</td>
                       <td class="px-3 py-3 whitespace-nowrap text-sm 
text-blue-600 font-semibold">${price.toFixed(2)}</td>
                       <td class="px-3 py-3 whitespace-nowrap text-sm"><span 
class="${stockColor} font-bold">${stock}</span></td>
                       <td class="px-3 py-3 whitespace-nowrap text-sm 
text-green-700">${profitPerUnit}</td>
                   `;
                   inventoryBody.appendChild(row);
               });
           }
           
           // 18. تحديث قيمة البيع الإجمالية والدفع الآجل (بيع)
           function updateSaleValue() {
               const itemId = document.getElementById('sale-item-id').value;
               const quantity = 
parseInt(document.getElementById('sale-quantity').value, 10) || 0;
               const immediatePayment = 
parseFloat(document.getElementById('sale-immediate-payment').value) || 0;
   
               const selectedItem = inventoryItems.find(item => item.id === 
itemId);
               
               let totalValue = 0;
               let deferredPayment = 0;
   
               if (selectedItem) {
                   totalValue = selectedItem.price * quantity;
                   deferredPayment = Math.max(0, totalValue - immediatePayment);
               }
   
               document.getElementById('sale-total-value').textContent = 
totalValue.toFixed(2);
               document.getElementById('sale-deferred-payment').textContent = 
deferredPayment.toFixed(2);
           }
           
           // 19. معالج نموذج تسجيل عملية البيع الجديدة (تم نقله)
           document.getElementById('new-sale-form').addEventListener('submit', 
async (event) => {
               event.preventDefault();
               if (!isAuthReady || !userId) {
                   showMessage("الرجاء انتظار تسجيل الدخول أولاً.", 'error', 
'sale-message');
                   return;
               }
   
               const itemId = document.getElementById('sale-item-id').value;
               const customerId = 
document.getElementById('sale-customer-id').value || null; 
               const quantity = 
parseInt(document.getElementById('sale-quantity').value, 10);
               const immediatePayment = 
parseFloat(document.getElementById('sale-immediate-payment').value);
               
               const selectedItem = inventoryItems.find(item => item.id === 
itemId);
   
               if (!selectedItem || quantity > selectedItem.stock) {
                   showMessage("المخزون غير كافٍ لإتمام عملية البيع.", 'error', 
'sale-message');
                   return;
               }
   
               const totalSaleValue = selectedItem.price * quantity;
               const deferredPayment = Math.max(0, totalSaleValue - 
immediatePayment);
               
               if (!customerId && totalSaleValue > immediatePayment) {
                    showMessage("في حالة البيع النقدي، يجب أن يكون الدفع العاجل 
مساوياً للقيمة الإجمالية.", 'error', 'sale-message');
                    return;
               }
   
               const costOfGoodsSold = selectedItem.costPrice * quantity;
               const profitRealized = totalSaleValue - costOfGoodsSold; 
               let customerName = customerId ? customersList.find(c => c.id === 
customerId)?.name : 'بيع نقدي';
   
               try {
                   // 1. تحديث المخزون (خصم الكمية)
                   const itemRef = doc(db, inventoryCollectionPath, itemId);
                   await updateDoc(itemRef, { stock: increment(-quantity) });
   
                   // 2. تسجيل العملية في جدول المبيعات
                   await addDoc(collection(db, salesCollectionPath), {
                       itemId: itemId, itemName: selectedItem.name, customerId: 
customerId, customerName: customerName,
                       quantity: quantity, totalSaleValue: totalSaleValue, 
immediatePayment: immediatePayment, 
                       deferredPayment: deferredPayment, profitRealized: 
profitRealized, timestamp: serverTimestamp()
                   });
                   
                   // 3. تحديث دين الزبون 
                   if (deferredPayment > 0 && customerId) {
                       const customerRef = doc(db, customersCollectionPath, 
customerId);
                       await updateDoc(customerRef, { totalDebt: 
increment(deferredPayment) });
                   }
                   
                   document.getElementById('new-sale-form').reset();
                   updateSaleValue(); 
                   showMessage(`تم تسجيل عملية بيع ناجحة. الدين الآجل: 
${deferredPayment.toFixed(2)}`, 'success', 'sale-message');
   
               } catch (error) {
                   console.error("Error processing new sale:", error);
                   showMessage(`خطأ في إتمام عملية البيع: ${error.message}`, 
'error', 'sale-message');
               }
           });
   
   
           // 20. عرض رسائل المستخدم (عامة)
           function showMessage(message, type, elementId = 'add-item-message') {
               const messageDiv = document.getElementById(elementId);
               if (!messageDiv) return;
   
               messageDiv.textContent = message;
               messageDiv.classList.remove('hidden', 'text-green-600', 
'text-red-600', 'text-blue-600', 'text-purple-600');
               
               if (type === 'success') {
                   messageDiv.classList.add('text-green-600');
               } else if (type === 'error') {
                   messageDiv.classList.add('text-red-600');
               } else if (type === 'info') {
                    messageDiv.classList.add('text-blue-600');
               } else if (type === 'warning') {
                    messageDiv.classList.add('text-purple-600');
               }
   
   
               messageDiv.classList.remove('hidden');
   
               setTimeout(() => {
                   messageDiv.classList.add('hidden');
               }, 5000);
           }
   
           // إطلاق تحديث قيمة البيع والشراء عند بدء التشغيل
           document.addEventListener('DOMContentLoaded', () => {
                updateSaleValue();
                updatePurchaseValue();
           });
   
       </script>
   </body>
   </html>
   
   <!--
   Please make sure the checklist boxes are all checked before submitting the 
PR. The checklist is intended as a quick reference, for complete details please 
see our Contributor Guidelines:
   
   http://cordova.apache.org/contribute/contribute_guidelines.html
   
   Thanks!
   -->
   
   ### Platforms affected
   
   
   
   ### Motivation and Context
   <!-- Why is this change required? What problem does it solve? -->
   <!-- If it fixes an open issue, please link to the issue here. -->
   
   
   
   ### Description
   <!-- Describe your changes in detail -->
   
   
   
   ### Testing
   <!-- Please describe in detail how you tested your changes. -->
   
   
   
   ### Checklist
   
   - [ ] I've run the tests to see all new and existing tests pass
   - [ ] I added automated test coverage as appropriate for this change
   - [ ] Commit is prefixed with `(platform)` if this change only applies to 
one platform (e.g. `(android)`)
   - [ ] If this Pull Request resolves an issue, I linked to the issue in the 
text above (and used the correct [keyword to close issues using 
keywords](https://help.github.com/articles/closing-issues-using-keywords/))
   - [ ] I've updated the documentation if necessary
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to