import psycopg2

conn = psycopg2.connect(
    host="192.168.0.61",
    port=55432,
    database="njts_acct",
    user="njts_app",
    password="njts_app2025"
)

cur = conn.cursor()

print("=" * 100)
print("ID 444 と ID 445 の修正歷")
print("=" * 100)

for check_id in [444, 445]:
    print(f"\n【ID {check_id} の修正チェーン】")
    
    # 本人以及、original_entry_id を通じて関連する仕訳を取得
    cur.execute("""
        SELECT 
            je.journal_entry_id,
            je.entry_date,
            je.description,
            je.revision_count,
            je.is_latest,
            je.is_deleted,
            je.original_entry_id,
            COALESCE(SUM(jl.debit), 0) as debit_total,
            COALESCE(SUM(jl.credit), 0) as credit_total
        FROM journal_entries je
        LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
        WHERE (je.journal_entry_id = %s OR je.original_entry_id = %s OR %s IN (
            SELECT je2.journal_entry_id FROM journal_entries je2 WHERE je2.original_entry_id IN (
                SELECT journal_entry_id FROM journal_entries WHERE journal_entry_id = %s OR original_entry_id = %s
            )
        ))
        GROUP BY je.journal_entry_id, je.entry_date, je.description, je.revision_count, je.is_latest, je.is_deleted, je.original_entry_id
        ORDER BY je.journal_entry_id ASC
    """, (check_id, check_id, check_id, check_id, check_id))
    
    results = cur.fetchall()
    
    if results:
        for entry_id, entry_date, description, rev_count, is_latest, is_deleted, original_id, debit, credit in results:
            deleted_mark = "【削除】" if is_deleted else "      "
            latest_mark = "✓" if is_latest else "✗"
            orig_note = f"(orig={original_id})" if original_id else "(original)"
            print(f"  ID={entry_id:3d} {entry_date} {deleted_mark} [{latest_mark}v{rev_count}] {orig_note} | 借={debit:>10,.0f}  貸={credit:>10,.0f} | {description}")

cur.close()
conn.close()
