import psycopg2
from psycopg2.extras import RealDictCursor

conn = psycopg2.connect('host=192.168.0.61 port=55432 dbname=njts_acct user=njts_app password=njts_app2025')
cur = conn.cursor(cursor_factory=RealDictCursor)

print("=" * 80)
print("6月/7月/8月の試算表（修復後）")
print("=" * 80)

# 各月の売上高（account_id = 41）の試算表金額を確認
for month, year in [(6, 2025), (7, 2025), (8, 2025)]:
    # LEFT JOIN with parent filtering to exclude child entries
    cur.execute('''
SELECT 
  SUM(CASE WHEN jl.debit::numeric > 0 THEN jl.debit::numeric ELSE 0 END) as debit_total,
  SUM(CASE WHEN jl.credit::numeric > 0 THEN jl.credit::numeric ELSE 0 END) as credit_total
FROM journal_lines jl
JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
LEFT JOIN journal_entries child ON child.parent_entry_id = je.journal_entry_id
WHERE jl.account_id = 41  -- 売上高
  AND EXTRACT(YEAR FROM je.entry_date) = %s
  AND EXTRACT(MONTH FROM je.entry_date) = %s
  AND je.is_deleted = false
  AND child.journal_entry_id IS NULL  -- 親エントリのフィルター
''', (year, month))
    
    result = cur.fetchone()
    debit = result['debit_total'] if result['debit_total'] else 0
    credit = result['credit_total'] if result['credit_total'] else 0
    
    print(f"\n{year}年{month:2d}月: 借: {debit:>12,.0f} | 貳: {credit:>12,.0f}")

conn.close()
print("\n" + "=" * 80)
print("期待される結果：")
print("  6月: 借: 0 | 貳: 4,082,728 ✓")
print("  7月: 借: 0 | 貳: 8,082,728 ✓")
print("  8月: 借: 0 | 貳: 5,802,728 ✓")
print("=" * 80)
