#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
sys.path.insert(0, 'backend')

os.environ['DB_HOST'] = '192.168.0.61'
os.environ['DB_NAME'] = 'njts_acct'
os.environ['DB_USER'] = 'njts_app'
os.environ['DB_PASSWORD'] = 'njts_app2025'
os.environ['DB_PORT'] = '55432'

from app.core.database import get_connection
from decimal import Decimal

with get_connection() as conn:
    with conn.cursor() as cur:
        print('\n【 2025年6月701科目的全部交易记录 】')
        cur.execute("""
            SELECT 
              jl.journal_line_id,
              jl.journal_entry_id,
              je.entry_date,
              je.description,
              jl.debit,
              jl.credit,
              je.parent_entry_id,
              je.is_deleted,
              (SELECT COUNT(*) FROM journal_entries child WHERE child.parent_entry_id = je.journal_entry_id) as has_child
            FROM journal_lines jl
            JOIN journal_entries je ON je.journal_entry_id = jl.journal_entry_id
            JOIN accounts ac ON ac.account_id = jl.account_id
            WHERE ac.account_code = '701'
              AND je.entry_date >= '2025-06-01'
              AND je.entry_date <= '2025-06-30'
            ORDER BY je.entry_date, je.journal_entry_id
        """)
        
        total_credit = 0
        credit_with_filter = 0
        
        for row in cur.fetchall():
            print(f"{row['entry_date']} | Entry#{row['journal_entry_id']:>3} | Debit={row['debit']:>10} | Credit={row['credit']:>10} | Parent={row['parent_entry_id']} | HasChild={row['has_child']} | Desc:{row['description']}")
            total_credit += row['credit']
            
            # 只有parent_entry_id IS NULL时才会被LEFT JOIN过滤包含
            if row['parent_entry_id'] is None and row['has_child'] == 0 and not row['is_deleted']:
                credit_with_filter += row['credit']
        
        print(f"\n总计:")
        print(f"  全部交易credit合计: {total_credit}")
        print(f"  过滤后credit合计(no parent, no child): {credit_with_filter}")
        print(f"  差异: {total_credit - credit_with_filter}")
        print(f"  预期值: 4,082,728")
