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("=" * 100)
print("7月と8月のすべてのEntry（完全な対冲チェーン）")
print("=" * 100)

# 7月/8月の全Entry を見て、どのエントリが関連しているか確認
cur.execute('''
SELECT 
  je.journal_entry_id,
  je.entry_date,
  je.description,
  je.parent_entry_id,
  jl.account_id,
  a.account_code,
  SUM(CASE WHEN jl.debit::numeric > 0 THEN jl.debit::numeric ELSE 0 END) as debit,
  SUM(CASE WHEN jl.credit::numeric > 0 THEN jl.credit::numeric ELSE 0 END) as credit
FROM journal_entries je
LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
LEFT JOIN accounts a ON jl.account_id = a.account_id
WHERE EXTRACT(MONTH FROM je.entry_date) IN (7, 8)
  AND EXTRACT(YEAR FROM je.entry_date) = 2025
  AND je.is_deleted = false
  AND jl.account_id IN (41, 201)  -- 売上高 と 売掛金
GROUP BY je.journal_entry_id, je.entry_date, je.description, je.parent_entry_id, jl.account_id, a.account_code
ORDER BY je.journal_entry_id, jl.account_id
''')

rows = cur.fetchall()
for row in rows:
    account_info = f"({row['account_code']}) " if row['account_code'] else ""
    parent_str = f"parent={row['parent_entry_id']}" if row['parent_entry_id'] else "parent=None"
    debit = row['debit'] if row['debit'] else 0
    credit = row['credit'] if row['credit'] else 0
    print(f"\nEntry#{row['journal_entry_id']}: {row['entry_date']} | {account_info} 借: {debit:>10,.0f} 貳: {credit:>10,.0f} | {parent_str}")
    print(f"  Description: {row['description']}")

print("\n" + "=" * 100)
print("対冲分析：")
print("  Entry#358 (正): 売上1.4M貳, 売掛金1.54M借")
print("  Entry#361 (取消): 売上1.4M借, 売掛金1.54M貳 [parent=358] ✓")
print("  → 7月は完全に対冲されるはずだが、なぜまだ1.4Mが残っている？")
print("\n  Entry#359 (正): 売上1.4M貳, 売掛金1.54M借")
print("  Entry#362 (取消): 売上1.4M借, 売掛金1.54M貳 [parent=359] ✓")
print("  → 8月も同じ状态")
print("=" * 100)

conn.close()
