feat(project): 업무 휴지통(3개월 보관·관리자 복구) + 하위 업무 우클릭 삭제

- 업무 삭제 시 지우기 직전 스냅샷(업무·하위 업무·댓글·팔로워·@태그·첨부
  기록·연결·활동 이력·마감 알림 기록)을 같은 트랜잭션에서 project_trash 에
  JSONB 로 남기고 삭제. 첨부 실물은 DATA_DIR/project/_trash/<id>/ 로 이동.
- 관리자 전용 휴지통(/project/trash, 좌측 메뉴): 원래 id 그대로 복구(중복·
  지워진 프로젝트·상위 없는 하위는 거부, 지워진 세션은 미지정으로).
  3개월 지난 항목은 휴지통 화면/삭제 때 영구 정리.
- 삭제 확인 공용화(confirmTaskDelete): 하위 업무가 있으면 'N개까지 모두
  삭제' 를 명확히 묻고, 휴지통 보관 안내. 카드 하위 업무 우클릭 메뉴
  (열기/완료/하위 업무 삭제).
- DB: project_db_010_trash.sql. 미적용이면 예전처럼 영구 삭제.
- 로컬 PostgreSQL 17 로 삭제→휴지통→복구·거부 조건·만료 정리 검증.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-24 00:51:33 +09:00
parent 624145de56
commit 56250e6027
12 changed files with 563 additions and 23 deletions
+166 -2
View File
@@ -20,6 +20,7 @@ from typing import Any
from psycopg import errors as psycopg_errors
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
from psycopg_pool import ConnectionPool
from app.timezone import KST, now_kst
@@ -772,8 +773,48 @@ class ProjectStore:
out["_newly_completed"] = newly_completed
return out
def delete_task(self, *, task_id: int) -> list[int]:
"""업무(+하위 업무 CASCADE) 삭제. 지워진 업무 id 목록 반환 — 첨부 폴더 정리용."""
# ════════════════════════════════════════════════════════════
# 휴지통 (마이그레이션 010) — 지우기 직전 스냅샷, 관리자 복구, 3개월 보관
# ════════════════════════════════════════════════════════════
# 업무에 딸린 테이블(task_id 로 묶임). 복구 때 이 순서대로 다시 넣는다 —
# task_mentions·task_attachments 의 comment_id 가 댓글을 가리키므로 댓글 먼저.
# 알림(project_notifications)은 되살리면 수신함에 옛 알림이 다시 쌓여 제외.
TRASH_CHILD_TABLES = (
"task_comments", "task_followers", "task_mentions", "task_attachments",
"task_project_links", "project_activity", "task_reminders",
)
@staticmethod
def _table_exists(conn: Any, name: str) -> bool:
row = conn.execute("SELECT to_regclass(%s) AS r", (f"public.{name}",)).fetchone()
return bool(row and row["r"])
def _trash_snapshot(self, conn: Any, ids: list[int]) -> dict[str, list[dict[str, Any]]]:
"""업무 id 묶음과 딸린 행 전부를 JSON 으로(to_jsonb). 없는 테이블은 건너뜀."""
payload: dict[str, list[dict[str, Any]]] = {}
row = conn.execute(
"SELECT COALESCE(jsonb_agg(to_jsonb(x) ORDER BY x.id), '[]'::jsonb) AS j "
"FROM tasks x WHERE x.id = ANY(%s)",
(ids,),
).fetchone()
payload["tasks"] = row["j"]
for table in self.TRASH_CHILD_TABLES:
if not self._table_exists(conn, table):
continue
row = conn.execute(
f"SELECT COALESCE(jsonb_agg(to_jsonb(x)), '[]'::jsonb) AS j "
f"FROM {table} x WHERE x.task_id = ANY(%s)",
(ids,),
).fetchone()
payload[table] = row["j"]
return payload
def delete_task(self, *, task_id: int, deleted_by: str = "") -> tuple[list[int], int | None]:
"""업무(+하위 업무 CASCADE) 삭제 → (지워진 업무 id 목록, 휴지통 id).
휴지통 테이블(010)이 있으면 지우기 직전 스냅샷을 같은 트랜잭션에서 남긴다
(스냅샷 저장이 실패하면 삭제도 취소). 없으면 휴지통 id 는 None — 예전처럼
영구 삭제. 첨부 폴더는 라우터가 휴지통으로 옮기거나 지운다."""
with self._pool.connection() as conn:
with conn.transaction():
rows = conn.execute(
@@ -784,11 +825,134 @@ class ProjectStore:
") SELECT id FROM sub",
(task_id,),
).fetchall()
ids = [int(r["id"]) for r in rows]
if not ids:
raise KeyError(task_id)
trash_id: int | None = None
if self._table_exists(conn, "project_trash"):
root = conn.execute(
"SELECT t.title, t.project_id, p.name AS project_name "
"FROM tasks t LEFT JOIN projects p ON p.id = t.project_id WHERE t.id = %s",
(task_id,),
).fetchone()
payload = self._trash_snapshot(conn, ids)
trow = conn.execute(
"INSERT INTO project_trash "
"(task_id, project_id, project_name, title, task_count, deleted_by, payload) "
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id",
(task_id, root["project_id"], root["project_name"] or "", root["title"] or "",
len(ids), store.norm_str(deleted_by, lower=True), Jsonb(payload)),
).fetchone()
trash_id = int(trow["id"])
cur = conn.execute("DELETE FROM tasks WHERE id = %s", (task_id,))
if cur.rowcount == 0:
raise KeyError(task_id)
return ids, trash_id
def trash_enabled(self) -> bool:
with self._pool.connection() as conn:
return self._table_exists(conn, "project_trash")
def list_trash(self) -> list[dict[str, Any]]:
"""휴지통 목록(최근 삭제순). payload 는 빼고 요약만."""
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT id, task_id, project_id, project_name, title, task_count, deleted_by, "
" deleted_at, expires_at, "
" jsonb_array_length(COALESCE(payload->'task_comments', '[]'::jsonb)) AS comment_count, "
" jsonb_array_length(COALESCE(payload->'task_attachments', '[]'::jsonb)) AS attachment_count "
"FROM project_trash ORDER BY deleted_at DESC, id DESC"
).fetchall()
return [self._serialize(r) for r in rows]
def purge_expired_trash(self) -> list[int]:
"""보관 기간(expires_at)이 지난 휴지통 항목 영구 삭제 → 지운 휴지통 id 목록
(라우터가 그 휴지통 폴더를 지운다)."""
with self._pool.connection() as conn:
rows = conn.execute(
"DELETE FROM project_trash WHERE expires_at < now() RETURNING id"
).fetchall()
return [int(r["id"]) for r in rows]
def _insert_snapshot_rows(self, conn: Any, table: str, rows: list[dict[str, Any]]) -> None:
"""스냅샷 행을 원래 id 그대로 다시 넣는다. 지금 테이블에 있는 열만(이후 추가된
열은 기본값). table 은 TRASH_CHILD_TABLES/tasks 화이트리스트에서만 온다."""
if not rows:
return
live = {
r["column_name"] for r in conn.execute(
"SELECT column_name FROM information_schema.columns "
"WHERE table_schema = 'public' AND table_name = %s",
(table,),
).fetchall()
}
cols = [c for c in rows[0].keys() if c in live]
collist = ", ".join(f'"{c}"' for c in cols)
conflict = "" if table == "tasks" else " ON CONFLICT DO NOTHING"
conn.execute(
f"INSERT INTO {table} ({collist}) "
f"SELECT {collist} FROM jsonb_populate_recordset(NULL::{table}, %s){conflict}",
(Jsonb(rows),),
)
def restore_trash(self, *, trash_id: int, restored_by: str = "") -> dict[str, Any]:
"""휴지통 항목 복구 → {"task_id", "project_id", "task_ids"}. 성공하면 휴지통
행은 지운다. 복구할 수 없으면 ValueError(사유), 없으면 KeyError.
- 같은 id 의 업무가 이미 있으면 거부(두 번 복구 방지).
- 프로젝트가 지워졌으면 거부. 하위 업무만 지웠던 경우 상위 업무가 없으면 거부.
- 세션이 지워졌으면 세션 없이(미지정), 연결/이력 중 지워진 프로젝트를
가리키는 행은 뺀다."""
with self._pool.connection() as conn:
with conn.transaction():
tr = conn.execute(
"SELECT * FROM project_trash WHERE id = %s FOR UPDATE", (trash_id,)
).fetchone()
if not tr:
raise KeyError(trash_id)
payload = tr["payload"] or {}
tasks = list(payload.get("tasks") or [])
if not tasks:
raise ValueError("복구할 업무 데이터가 없습니다.")
ids = [int(t["id"]) for t in tasks]
clash = conn.execute(
"SELECT id FROM tasks WHERE id = ANY(%s) LIMIT 1", (ids,)
).fetchone()
if clash:
raise ValueError(f"이미 같은 업무(id {clash['id']})가 있어 복구할 수 없습니다.")
project_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM projects").fetchall()}
stage_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM project_stages").fetchall()}
root = next((t for t in tasks if int(t["id"]) == int(tr["task_id"])), tasks[0])
if int(root["project_id"]) not in project_ids:
raise ValueError("업무가 속했던 프로젝트가 삭제되어 복구할 수 없습니다.")
parent = root.get("parent_task_id")
if parent and int(parent) not in ids:
ok = conn.execute("SELECT 1 FROM tasks WHERE id = %s", (int(parent),)).fetchone()
if not ok:
raise ValueError("상위 업무가 없어 복구할 수 없습니다 — 상위 업무를 먼저 복구하세요.")
for t in tasks:
if t.get("stage_id") is not None and int(t["stage_id"]) not in stage_ids:
t["stage_id"] = None
self._insert_snapshot_rows(conn, "tasks", tasks)
for table in self.TRASH_CHILD_TABLES:
rows = list(payload.get(table) or [])
if not rows or not self._table_exists(conn, table):
continue
kept = []
for r in rows:
pid = r.get("project_id")
if pid is not None and int(pid) not in project_ids:
continue
if table == "task_project_links" and r.get("stage_id") is not None \
and int(r["stage_id"]) not in stage_ids:
r["stage_id"] = None
kept.append(r)
self._insert_snapshot_rows(conn, table, kept)
self._log(conn, project_id=int(root["project_id"]), task_id=int(root["id"]),
actor=restored_by, action="restored", detail=f"휴지통에서 복구: {root.get('title') or ''}")
conn.execute("DELETE FROM project_trash WHERE id = %s", (trash_id,))
return {"task_id": int(root["id"]), "project_id": int(root["project_id"]), "task_ids": ids}
def _stage_is_done(self, stage_id: Any) -> bool:
if stage_id is None:
return False