This commit is contained in:
FNOS-WIN11ENT\choshoukaku
2025-12-18 15:30:39 +09:00
parent 88163423e0
commit 87fa1aaa1f
12 changed files with 742 additions and 192 deletions

View File

@@ -19,24 +19,69 @@ class JournalEntryRequest(BaseModel):
description: str
lines: List[JournalLine]
class JournalEntryUpdateRequest(BaseModel):
description: str
lines: List[JournalLine]
updated_reason: str
@router.post("")
class JournalEntryDeleteRequest(BaseModel):
deleted_reason: str
@router.post("", summary="仕訳登録")
def create_journal_entry(req: JournalEntryRequest):
from app.utils.month_lock import is_month_locked
if is_month_locked(req.entry_date):
raise HTTPException(
status_code=400,
detail="该月份已锁定,不能新增仕訳"
)
if not req.lines:
raise HTTPException(status_code=400, detail="仕訳明細不能为空")
# (可选)简单的借贷平衡校验
total_debit = sum(l.debit for l in req.lines)
total_credit = sum(l.credit for l in req.lines)
if total_debit != total_credit:
raise HTTPException(status_code=400, detail="借方和贷方不平衡")
fiscal_year = req.entry_date.year
with get_connection() as conn:
with conn.cursor() as cur:
# 仕訳ヘッダ
cur.execute("""
INSERT INTO journal_entries (entry_date, description)
VALUES (%s, %s)
RETURNING id
""", (req.entry_date, req.description))
entry_id = cur.fetchone()[0]
INSERT INTO journal_entries (
journal_date,
description,
fiscal_year,
version,
is_deleted,
created_by
)
VALUES (%s, %s, %s, 1, false, %s)
RETURNING journal_id
""", (
req.entry_date,
req.description,
fiscal_year,
"system" # 以后可以换成登录用户
))
entry_id = cur.fetchone()["journal_id"]
# 明細
for line in req.lines:
cur.execute("""
INSERT INTO journal_lines
(journal_entry_id, account_id, debit, credit)
INSERT INTO journal_lines (
journal_id,
account_id,
debit,
credit
)
VALUES (%s, %s, %s, %s)
""", (
entry_id,
@@ -47,4 +92,121 @@ def create_journal_entry(req: JournalEntryRequest):
conn.commit()
return {"status": "ok", "journal_entry_id": entry_id}
return {
"status": "ok",
"journal_entry_id": entry_id
}
@router.put("/{journal_id}")
def update_journal_entry(journal_id: int, req: JournalEntryUpdateRequest):
from app.utils.month_lock import is_month_locked
with get_connection() as conn:
with conn.cursor() as cur:
# ① 取得现有仕訳
cur.execute("""
SELECT journal_date, is_deleted, version
FROM journal_entries
WHERE journal_id = %s
""", (journal_id,))
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="仕訳が存在しません")
if row["is_deleted"]:
raise HTTPException(status_code=400, detail="削除済み仕訳は更新できません")
journal_date = row["journal_date"]
# 借贷平衡校验update
total_debit = sum(l.debit for l in req.lines)
total_credit = sum(l.credit for l in req.lines)
if total_debit != total_credit:
raise HTTPException(status_code=400, detail="借方和贷方不平衡")
# ② 月次锁定检查
if is_month_locked(journal_date):
raise HTTPException(status_code=400, detail="该月份已锁定,不能修改仕訳")
# ③ 更新 header
cur.execute("""
UPDATE journal_entries
SET description = %s,
version = version + 1,
updated_at = NOW(),
updated_reason = %s
WHERE journal_id = %s
""", (
req.description,
req.updated_reason,
journal_id
))
# ④ 删除原有明细物理删除OK
cur.execute("""
DELETE FROM journal_lines
WHERE journal_id = %s
""", (journal_id,))
# ⑤ 插入新明细
for line in req.lines:
cur.execute("""
INSERT INTO journal_lines (
journal_id,
account_id,
debit,
credit
) VALUES (%s, %s, %s, %s)
""", (
journal_id,
line.account_id,
line.debit,
line.credit
))
conn.commit()
return {
"status": "ok",
"journal_id": journal_id,
"message": "仕訳を更新しました"
}
@router.delete("/{journal_id}", summary="仕訳删除(软删除)")
def delete_journal_entry(journal_id: int, req: JournalEntryDeleteRequest):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute("""
UPDATE journal_entries
SET is_deleted = true,
deleted_at = NOW(),
deleted_reason = %s
WHERE journal_id = %s
AND is_deleted = false
RETURNING journal_id
""", (
req.deleted_reason,
journal_id
))
row = cur.fetchone()
if not row:
raise HTTPException(
status_code=404,
detail="仕訳不存在,或已被删除"
)
conn.commit()
return {
"status": "deleted",
"journal_entry_id": journal_id
}

View File

@@ -0,0 +1,93 @@
from fastapi import APIRouter, HTTPException
from app.core.database import get_connection
router = APIRouter(prefix="/month-locks", tags=["月次锁定"])
# ---------- GET月次锁定一覧 ----------
@router.get("", summary="月次锁定一覧取得")
def get_month_locks():
with get_connection() as conn, conn.cursor() as cur:
cur.execute("""
SELECT
fiscal_year,
month,
is_locked,
locked_at,
locked_by
FROM month_locks
ORDER BY fiscal_year, month
""")
return cur.fetchall()
# ---------- POST锁定月份 ----------
@router.post("/lock", summary="锁定月份")
def lock_month(fiscal_year: int, month: int):
# 参数校验
if not (1 <= month <= 12):
raise HTTPException(status_code=400, detail="month 必须是 112")
with get_connection() as conn, conn.cursor() as cur:
cur.execute("""
INSERT INTO month_locks (
fiscal_year,
month,
is_locked,
locked_at,
locked_by
)
VALUES (%s, %s, true, NOW(), %s)
ON CONFLICT (fiscal_year, month)
DO UPDATE
SET is_locked = true,
locked_at = NOW(),
locked_by = EXCLUDED.locked_by
""", (
fiscal_year,
month,
"system" # 将来可替换为登录用户
))
conn.commit()
return {
"status": "locked",
"fiscal_year": fiscal_year,
"month": month
}
# ---------- POST解锁月份 ----------
@router.post("/unlock", summary="解锁月份")
def unlock_month(fiscal_year: int, month: int):
# 参数校验
if not (1 <= month <= 12):
raise HTTPException(status_code=400, detail="month 必须是 112")
with get_connection() as conn, conn.cursor() as cur:
cur.execute("""
UPDATE month_locks
SET is_locked = false
WHERE fiscal_year = %s
AND month = %s
""", (
fiscal_year,
month
))
if cur.rowcount == 0:
raise HTTPException(
status_code=404,
detail="指定月份不存在"
)
conn.commit()
return {
"status": "unlocked",
"fiscal_year": fiscal_year,
"month": month
}

View File

@@ -0,0 +1,59 @@
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