import psycopg2

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

cur = conn.cursor()

# 首先检查account 102是否存在
cur.execute("""
    SELECT account_id, account_code, account_name 
    FROM accounts 
    WHERE account_code = '102'
""")
account_info = cur.fetchone()
print(f"Account 102: {account_info}")

if account_info:
    account_id = account_info[0]
    
    # 查询普通預金 2025年8月的所有仕訳
    cur.execute("""
        SELECT 
            je.journal_entry_id,
            je.entry_date,
            je.description,
            je.revision_count,
            je.is_latest,
            je.is_deleted,
            jl.debit,
            jl.credit
        FROM journal_entries je
        LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
        WHERE je.entry_date >= '2025-08-01' 
          AND je.entry_date < '2025-09-01'
          AND jl.account_id = %s
        ORDER BY je.entry_date DESC, je.journal_entry_id DESC
    """, (account_id,))
    
    results = cur.fetchall()
    
    print("\n" + "=" * 100)
    print("普通預金 2025年8月 全仕訳（削除フラグ関わらず）")
    print("=" * 100)
    
    if results:
        total_debit = 0
        total_credit = 0
        latest_total_debit = 0
        latest_total_credit = 0
        
        for entry_id, entry_date, description, rev_count, is_latest, is_deleted, debit, credit in results:
            debit = debit or 0
            credit = credit or 0
            total_debit += debit
            total_credit += credit
            
            if is_latest:
                latest_total_debit += debit
                latest_total_credit += credit
            
            deleted_mark = "【削除】" if is_deleted else "      "
            latest_mark = "✓" if is_latest else "✗"
            print(f"{entry_date} {deleted_mark} [{latest_mark}v{rev_count}] ID={entry_id}: {description[:50]}")
            print(f"           借={debit:>15,.0f}  貸={credit:>15,.0f}")
        
        print(f"\n全体合計: 借={total_debit:>15,.0f}  貸={total_credit:>15,.0f}")
        print(f"is_latest=true のみ: 借={latest_total_debit:>15,.0f}  貸={latest_total_credit:>15,.0f}")

cur.close()
conn.close()
