Files
njts-accounting-core/backend/app/routers/trial_balance.py
FNOS-WIN11ENT\choshoukaku 87fa1aaa1f 修正
2025-12-18 15:30:39 +09:00

60 lines
1.7 KiB
Python

from fastapi import APIRouter, Query
from datetime import date
from typing import Optional
from app.core.database import get_connection
router = APIRouter(prefix="/trial-balance", tags=["试算表"])
@router.get("", summary="试算表(全科目)")
def get_trial_balance(
fiscal_year: Optional[int] = Query(None, description="会计年度(可选)"),
date_from: Optional[date] = Query(None, description="开始日期(可选)"),
date_to: Optional[date] = Query(None, description="结束日期(可选)"),
):
print("### trial-balance OPTIONAL PARAMS ACTIVE ###")
sql = """
SELECT
a.account_id,
a.account_code,
a.account_name,
a.account_type,
COALESCE(SUM(l.debit), 0) AS debit,
COALESCE(SUM(l.credit), 0) AS credit
FROM journal_lines l
JOIN journal_entries e ON e.journal_id = l.journal_id
JOIN accounts a ON a.account_id = l.account_id
WHERE 1 = 1
"""
params = {}
if fiscal_year is not None:
sql += " AND e.fiscal_year = %(fiscal_year)s"
params["fiscal_year"] = fiscal_year
if date_from is not None:
sql += " AND e.journal_date >= %(date_from)s"
params["date_from"] = date_from
if date_to is not None:
sql += " AND e.journal_date <= %(date_to)s"
params["date_to"] = date_to
sql += """
GROUP BY
a.account_id,
a.account_code,
a.account_name,
a.account_type
ORDER BY
a.account_code
"""
with get_connection() as conn, conn.cursor() as cur:
cur.execute(sql, params)
rows = cur.fetchall()
return rows