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月の過濾详细分析（Entry#358 vs Entry#361）")
print("=" * 100)

# 7月の試算表クエリーの過濾ロジックを詳しく見る
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) as 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 jl.account_id = 41  -- 売上高
  AND EXTRACT(YEAR FROM je.entry_date) = 2025
  AND EXTRACT(MONTH FROM je.entry_date) = 7
  AND je.is_deleted = false
GROUP BY je.journal_entry_id, je.parent_entry_id
ORDER BY je.journal_entry_id
''')

rows = cur.fetchall()
print("\n【全Entry（フィルを考慮しない）】")
for row in rows:
    has_child = "はい" if row['child_count'] > 0 else "いいえ"
    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} | child: {has_child} ({row['child_count']}) | 借: {row['debit']:>10,.0f} 貳: {row['credit']:>10,.0f}")

# 實際のフィルーングを適用したクエリー
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
WHERE jl.account_id = 41  -- 売上高
  AND EXTRACT(YEAR FROM je.entry_date) = 2025
  AND EXTRACT(MONTH FROM je.entry_date) = 7
  AND je.is_deleted = false
  AND child.journal_entry_id IS NULL  -- フィルー：childがない場合のみ
GROUP BY je.journal_entry_id, je.parent_entry_id
ORDER BY je.journal_entry_id
''')

rows = cur.fetchall()
print("\n【フィルー後のEntry（child.journal_entry_id IS NULL）】")
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}")

print("\n【分析】")
print("  Entry#358: parent=None, child=Entry#361 → フィルー/表示されない ✓")
print("  Entry#361: parent=358, child=なし → 表示される ✗ (= 1.4M が殘ってる)")
print("\n【問題】")
print("  對冲の邏輯が逆！")
print("  - Entry#358（正） と Entry#361（取消）は両方過濾されるべき")
print("  - 現在のフィルーは、親を過濾して子を表示している")
print("=" * 100)

conn.close()
