This commit is contained in:
admin
2026-02-21 10:51:25 +09:00
parent 584530937b
commit 3b028b8fc0
25 changed files with 1852 additions and 244 deletions

View File

@@ -661,28 +661,71 @@ def update_journal_entry(journal_id: int, req: JournalEntryUpdateRequest):
@router.delete("/{journal_id}", summary="仕訳削除(ソフト削除)")
def delete_journal_entry(journal_id: int, req: JournalEntryDeleteRequest):
"""
仕訳をソフト削除し、is_latest フラグを自動更新
ポイント:
- original_entry_id を持つ版本チェーン全体は影響を受けない
- 削除されたのが最新版の場合、前の版本を新しい is_latest にする
- 軟削除is_deleted=trueなので完全な履歴は保持される
"""
with get_connection() as conn:
with conn.cursor() as cur:
# ① 削除対象の仕訳情報を取得
cur.execute("""
UPDATE journal_entries
SET is_deleted = true,
updated_at = CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Tokyo'
WHERE journal_entry_id = %s
AND is_deleted = false
RETURNING journal_entry_id
SELECT
journal_entry_id,
original_entry_id,
is_latest,
revision_count
FROM journal_entries
WHERE journal_entry_id = %s
AND is_deleted = false
""", (journal_id,))
row = cur.fetchone()
if not row:
raise HTTPException(
status_code=404,
detail="仕訳が存在しないか、既に削除されています"
)
original_entry_id = row["original_entry_id"]
is_latest = row["is_latest"]
# ② ソフト削除を実行
cur.execute("""
UPDATE journal_entries
SET is_deleted = true,
updated_at = CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Tokyo'
WHERE journal_entry_id = %s
""", (journal_id,))
# ③ 削除されたのが最新版の場合のみ、新しい最新版を設定
if is_latest:
# 同じ original_entry_id を持つ未削除版の中で、最新の revision_count を探す
cur.execute("""
SELECT journal_entry_id
FROM journal_entries
WHERE (original_entry_id = %s OR journal_entry_id = %s)
AND is_deleted = false
AND journal_entry_id != %s
ORDER BY revision_count DESC
LIMIT 1
""", (original_entry_id or journal_id, original_entry_id or journal_id, journal_id))
new_latest = cur.fetchone()
if new_latest:
cur.execute("""
UPDATE journal_entries
SET is_latest = true
WHERE journal_entry_id = %s
""", (new_latest["journal_entry_id"],))
conn.commit()
return {
"status": "deleted",
"journal_entry_id": journal_id
"journal_entry_id": journal_id,
"message": "仕訳を削除しました(完全な履歴は保持されます)"
}