import os import django from django.db.models import Sum # تنظیمات محیطی جنگو برای اجرای اسکریپت خارج از وب‌سرور # ⚠️ مهم: کلمه 'myproject' را با نام پوشه اصلی پروژه خود (که فایل settings.py در آن است) جایگزین کنید. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'khatibi.settings') django.setup() # ایمپورت مدل‌ها بعد از راه‌اندازی محیط جنگو from admin_panel.models import Article, Sarresid, Customer def check_financial_discrepancy(): print("\n" + "="*50) print(" 🔍 در حال محاسبه و مقایسه اطلاعات مالی سیستم...") print("="*50 + "\n") # ۱. محاسبه تراز کل دفتر (mandehesab) بر اساس ستون‌های debit و credit[cite: 3] articles_agg = Article.objects.aggregate(total_debit=Sum('debit'), total_credit=Sum('credit')) total_debit = articles_agg['total_debit'] or 0 total_credit = articles_agg['total_credit'] or 0 total_mandehesab = total_debit - total_credit # ۲. محاسبه مجموع اسناد پرداخت‌نشده (چک‌ها و نسیه‌ها)[cite: 3] sarresid_agg = Sarresid.objects.filter(payStatus="false").aggregate(total_price=Sum('price')) total_sarresid = sarresid_agg['total_price'] or 0 # ۳. محاسبه اختلاف بین دفتر کل و اسناد در دست discrepancy = total_mandehesab - total_sarresid print("📊 [ خلاصه وضعیت کل سیستم ]") print("-" * 40) print(f"💰 تراز کل دفتر کل (mandehesab): {total_mandehesab:,} ریال") print(f"📑 مجموع اسناد و چک‌های در دست: {total_sarresid:,} ریال") print(f"⚠️ کل اختلاف (بدهی‌های بدون سند): {discrepancy:,} ریال") print("-" * 40 + "\n") # ۴. تحلیل به تفکیک مشتریان برای پیدا کردن منشا اختلاف print("🔎 [ لیست مشتریان دارای بدهی باز (منشأ اختلاف) ]") print("-" * 40) customers = Customer.objects.filter(is_active=True) count = 0 for customer in customers: # الف: محاسبه مانده حساب این مشتری c_agg = Article.objects.filter(customer=customer).aggregate(t_d=Sum('debit'), t_c=Sum('credit')) c_debit = c_agg['t_d'] or 0 c_credit = c_agg['t_c'] or 0 c_mandehesab = c_debit - c_credit # ب: محاسبه سررسیدهای پرداخت نشده این مشتری s_agg = Sarresid.objects.filter(customer=customer, payStatus="false").aggregate(t_p=Sum('price')) c_sarresid = s_agg['t_p'] or 0 # ج: بررسی اختلاف c_diff = c_mandehesab - c_sarresid # اگر اختلاف بیشتر از صفر بود، یعنی مشتری بدهی رو هوا (بدون سند) دارد if c_diff > 0: count += 1 print(f"👤 {customer.name_family} (کد: {customer.id})") print(f" ↳ تراز کل: {c_mandehesab:,} | اسناد: {c_sarresid:,} | مبلغ اختلاف: {c_diff:,}") print("-" * 20) if count == 0: print("✅ هیچ مشتری با بدهی دفتری (بدون سند) یافت نشد. حساب‌ها تراز است.") else: print(f"\nتعداد کل مشتریان دارای اختلاف حساب: {count} نفر") if __name__ == '__main__': check_financial_discrepancy()