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("【重要】過濾クエリーのチェック")
print("=" * 100)

print("\n【Entry#360の child を確認（deleted含む）】")
cur.execute('''
SELECT 
  journal_entry_id,
  parent_entry_id,
  is_deleted,
  description
FROM journal_entries
WHERE parent_entry_id = 360
ORDER BY journal_entry_id
''')

rows = cur.fetchall()
for row in rows:
    deleted_str = "削除済み" if row['is_deleted'] else "有効"
    print(f"  Entry#{row['journal_entry_id']}: {deleted_str} | parent=360")
    print(f"    {row['description'][:60]}")

print("\n【Entry#357と#360のフィルー確認】")
cur.execute('''
SELECT 
  je.journal_entry_id,
  je.parent_entry_id,
  (
    SELECT COUNT(*) 
    FROM journal_entries child 
    WHERE child.parent_entry_id = je.journal_entry_id 
      AND child.is_deleted = false  -- 有効なchildのみ
  ) as valid_child_count,
  (
    SELECT COUNT(*) 
    FROM journal_entries child 
    WHERE child.parent_entry_id = je.journal_entry_id
      -- is_deleted を指定しない  
  ) as all_child_count,
  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
WHERE je.journal_entry_id IN (357, 360)
  AND jl.account_id = 41
  AND je.is_deleted = false
GROUP BY je.journal_entry_id, je.parent_entry_id
ORDER BY je.journal_entry_id
''')

rows = cur.fetchall()
for row in rows:
    print(f"\nEntry#{row['journal_entry_id']}: parent={row['parent_entry_id']}")
    print(f"  Valid child: {row['valid_child_count']}, All child: {row['all_child_count']}")
    print(f"  Amount: 借 {row['debit']:>10,.0f} | 貳 {row['credit']:>10,.0f}")

print("\n【試算表フィルーの実装確認】")
cur.execute('''
SELECT 
  je.journal_entry_id,
  je.parent_entry_id,
  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_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
  -- 注意：削除されたchildも含まれる可能性がある
WHERE jl.account_id = 41
  AND EXTRACT(YEAR FROM je.entry_date) = 2025
  AND EXTRACT(MONTH FROM je.entry_date) = 6
  AND je.is_deleted = false
  AND child.journal_entry_id IS NULL
GROUP BY je.journal_entry_id, je.parent_entry_id
ORDER BY je.journal_entry_id
''')

rows = cur.fetchall()
print("\n試算表に表示されるEntry（6月）：")
for row in rows:
    parent_str = f"parent={row['parent_entry_id']}" if row['parent_entry_id'] else "parent=None"
    print(f"  Entry#{row['journal_entry_id']}: {parent_str} | 借 {row['debit']:>10,.0f} | 貳 {row['credit']:>10,.0f}")

conn.close()
