#!/bin/bash
# Check is_latest values directly using docker exec

echo "=========================================="
echo "【检查ID=431和432的is_latest值】"
echo "=========================================="

docker exec njts_db psql -U postgres -d njts_accounting -c "
SELECT 
    journal_entry_id,
    description,
    is_latest,
    parent_entry_id
FROM journal_entries
WHERE journal_entry_id IN (431, 432)
ORDER BY journal_entry_id;
"

echo ""
echo "=========================================="
echo "【检查701科目的所有仕訳行及其is_latest值】"
echo "=========================================="

docker exec njts_db psql -U postgres -d njts_accounting -c "
SELECT 
    j.journal_entry_id,
    j.description,
    j.is_latest,
    COUNT(*) as line_count,
    COALESCE(SUM(l.debit), 0) as total_debit,
    COALESCE(SUM(l.credit), 0) as total_credit
FROM journal_lines l
JOIN journal_entries j ON j.journal_entry_id = l.journal_entry_id
JOIN accounts a ON a.account_id = l.account_id
WHERE a.account_code = '701'
AND j.is_deleted = false
GROUP BY j.journal_entry_id, j.description, j.is_latest
ORDER BY j.journal_entry_id;
"

echo ""
echo "=========================================="
echo "【按is_latest值统计701科目】"
echo "=========================================="

docker exec njts_db psql -U postgres -d njts_accounting -c "
SELECT 
    j.is_latest,
    COUNT(*) as entry_count,
    COALESCE(SUM(l.debit), 0) as total_debit,
    COALESCE(SUM(l.credit), 0) as total_credit
FROM journal_lines l
JOIN journal_entries j ON j.journal_entry_id = l.journal_entry_id
JOIN accounts a ON a.account_id = l.account_id
WHERE a.account_code = '701'
AND j.is_deleted = false
GROUP BY j.is_latest
ORDER BY j.is_latest DESC;
"
