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("遠達ビル相関の全仕訳（削除フラグ関わらず）")
print("=" * 100)

cur.execute("""
    SELECT 
        je.journal_entry_id,
        je.entry_date,
        je.description,
        je.revision_count,
        je.is_latest,
        je.is_deleted,
        COALESCE(SUM(CASE WHEN jl.account_id = 2 THEN jl.credit ELSE 0 END), 0) as account_2_credit
    FROM journal_entries je
    LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
    WHERE je.description LIKE '%遠達ビル%'
    GROUP BY je.journal_entry_id, je.entry_date, je.description, je.revision_count, je.is_latest, je.is_deleted
    ORDER BY je.journal_entry_id ASC
""")

results = cur.fetchall()

for entry_id, entry_date, description, rev_count, is_latest, is_deleted, acc2_credit in results:
    deleted_mark = "【削除】" if is_deleted else "      "
    latest_mark = "✓" if is_latest else "✗"
    print(f"ID={entry_id:3d} {entry_date} {deleted_mark} [{latest_mark}v{rev_count}] acc2_credit={acc2_credit:>10,.0f} | {description}")

print("\n試算表に計上される仕訳 (is_latest=true AND is_deleted=false)")
cur.execute("""
    SELECT 
        je.journal_entry_id,
        je.entry_date,
        je.description,
        COALESCE(SUM(CASE WHEN jl.account_id = 2 THEN jl.credit ELSE 0 END), 0) as account_2_credit
    FROM journal_entries je
    LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
    WHERE je.description LIKE '%遠達ビル%'
      AND je.is_latest = true
      AND je.is_deleted = false
    GROUP BY je.journal_entry_id, je.entry_date, je.description
    ORDER BY je.journal_entry_id ASC
""")

results2 = cur.fetchall()
total_credit = 0
for entry_id, entry_date, description, acc2_credit in results2:
    total_credit += acc2_credit
    print(f"ID={entry_id:3d} {entry_date} acc2_credit={acc2_credit:>10,.0f} | {description}")

print(f"\n合計: {total_credit:>10,.0f}")

cur.close()
conn.close()
