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
+147 -4
View File
@@ -44,7 +44,7 @@ from fastapi.responses import (
)
from psycopg.errors import UndefinedColumn
from app.timezone import today_kst
from app.timezone import KST, now_kst, today_kst
from . import store
@@ -150,6 +150,76 @@ def _remove_task_dirs(request: Request, task_ids: list[int]) -> None:
logger.warning("첨부 폴더 삭제 실패: %s", d)
def _project_data_dir(request: Request) -> Path:
return Path(str(getattr(request.app.state, "data_dir", "."))) / "project"
def _trash_dir(request: Request, trash_id: int) -> Path:
"""휴지통으로 옮긴 첨부 폴더 자리 — DATA_DIR/project/_trash/<trash_id>/<task_id>."""
return _project_data_dir(request) / "_trash" / str(int(trash_id))
def _move_task_dirs_to_trash(request: Request, task_ids: list[int], trash_id: int) -> None:
"""지운 업무들의 첨부 폴더를 휴지통 폴더로 옮긴다(복구 시 되돌림). 실패해도
삭제는 이미 끝났으므로 로그만."""
import shutil # noqa: WPS433
base = _project_data_dir(request)
dest_root = _trash_dir(request, trash_id)
for tid in task_ids:
src = base / str(int(tid))
if not src.is_dir():
continue
try:
dest_root.mkdir(parents=True, exist_ok=True)
shutil.move(str(src), str(dest_root / str(int(tid))))
except Exception: # noqa: BLE001
logger.warning("첨부 폴더 휴지통 이동 실패: %s", src)
def _restore_task_dirs(request: Request, trash_id: int) -> None:
"""휴지통 폴더의 첨부 폴더를 원래 자리(DATA_DIR/project/<task_id>)로 되돌린다."""
import shutil # noqa: WPS433
root = _trash_dir(request, trash_id)
if not root.is_dir():
return
base = _project_data_dir(request)
for d in root.iterdir():
if not d.is_dir():
continue
dest = base / d.name
try:
if dest.exists():
logger.warning("복구 대상 첨부 폴더가 이미 있음 — 건너뜀: %s", dest)
continue
shutil.move(str(d), str(dest))
except Exception: # noqa: BLE001
logger.warning("첨부 폴더 복구 실패: %s", d)
try:
root.rmdir()
except OSError:
pass
def _purge_trash(request: Request, st: Any) -> None:
"""보관 기간(3개월)이 지난 휴지통 항목과 그 첨부 폴더를 영구 삭제. 휴지통 화면을
열거나 업무를 지울 때 가볍게 돈다. 실패해도 본 작업은 막지 않는다."""
import shutil # noqa: WPS433
try:
purged = st.purge_expired_trash()
except Exception: # noqa: BLE001 - 010 미적용 등
return
for trash_id in purged:
d = _trash_dir(request, trash_id)
if d.is_dir():
try:
shutil.rmtree(d)
except Exception: # noqa: BLE001
logger.warning("휴지통 폴더 삭제 실패: %s", d)
def _admin_emails(request: Request) -> list[str]:
"""알림 수신 관리자 이메일 목록.
@@ -1256,11 +1326,16 @@ def api_delete_task(request: Request, task_id: int) -> JSONResponse:
if not _can_delete(user, existing.get("created_by")):
raise HTTPException(status_code=403, detail=_DELETE_DENIED)
try:
removed_task_ids = st.delete_task(task_id=task_id)
removed_task_ids, trash_id = st.delete_task(task_id=task_id, deleted_by=user["email"])
except KeyError:
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
_remove_task_dirs(request, removed_task_ids) # 하위 업무 첨부 폴더까지
return JSONResponse({"ok": True})
# 휴지통(010)이 있으면 첨부 폴더도 휴지통으로(복구 대비), 없으면 예전처럼 삭제.
if trash_id is not None:
_move_task_dirs_to_trash(request, removed_task_ids, trash_id)
else:
_remove_task_dirs(request, removed_task_ids) # 하위 업무 첨부 폴더까지
_purge_trash(request, st)
return JSONResponse({"ok": True, "trash": trash_id is not None, "count": len(removed_task_ids)})
@router.get("/api/tasks/{task_id}")
@@ -1843,6 +1918,74 @@ def api_mentions_read(
return JSONResponse({"ok": True, "marked": n})
@router.get("/trash", response_class=HTMLResponse)
def trash_page(request: Request) -> HTMLResponse:
"""휴지통 — 관리자 전용. 지운 업무(하위 업무 포함)를 3개월 보관, 복구."""
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
user = _require_user(request)
if not is_admin(user):
raise HTTPException(status_code=403, detail="관리자만 볼 수 있습니다.")
st = _store(request)
if st is None:
return _render_config_needed(request, user)
_purge_trash(request, st)
enabled = st.trash_enabled()
return render_template(
request,
"project/trash.html",
{
"user": user,
"is_admin": True,
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, True),
"my_open_total": st.count_my_open(assignee_email=user["email"]),
"mention_unread": _safe_mention_unread(st, user["email"]),
"page_title": "휴지통",
"page_subtitle": "삭제한 업무 — 3개월 보관, 관리자만 복구",
"force_sidebar_collapsed": True,
"trash_enabled": enabled,
"items": _trash_view_items(st.list_trash()) if enabled else [],
},
)
def _trash_view_items(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""휴지통 화면용 — 삭제 시각(KST 문자열)·남은 보관 일수."""
from datetime import datetime # noqa: WPS433
now = now_kst()
for it in items:
try:
deleted = datetime.fromisoformat(str(it["deleted_at"])).astimezone(KST)
it["deleted_label"] = deleted.strftime("%Y-%m-%d %H:%M")
except (TypeError, ValueError):
it["deleted_label"] = str(it.get("deleted_at") or "")[:16]
try:
expires = datetime.fromisoformat(str(it["expires_at"])).astimezone(KST)
it["days_left"] = max(0, (expires - now).days)
except (TypeError, ValueError):
it["days_left"] = None
it["deleted_by_id"] = (it.get("deleted_by") or "").split("@")[0]
return items
@router.post("/api/trash/{trash_id}/restore")
def api_restore_trash(request: Request, trash_id: int) -> JSONResponse:
"""휴지통 항목 복구 — 관리자 전용. 업무·하위 업무·댓글 등 원래 id 그대로."""
user = _require_admin(request)
st = _db_or_503(request)
try:
result = st.restore_trash(trash_id=trash_id, restored_by=user["email"])
except KeyError:
raise HTTPException(status_code=404, detail="휴지통 항목을 찾을 수 없습니다.")
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc))
_restore_task_dirs(request, trash_id)
return JSONResponse({"ok": True, **result})
@router.get("/inbox", response_class=HTMLResponse)
def inbox_page(request: Request) -> HTMLResponse:
from app.main import build_erp_nav, render_template # noqa: WPS433
@@ -6,7 +6,7 @@
my_open_total 진행 중인 내 업무 개수 (내 업무 배지)
nav_projects 프로젝트 목록(평면)
current_pid 지금 보고 있는 프로젝트 id (내 업무/수신함 화면이면 0)
side_active 'inbox' | 'mytasks' | '' — 개인 메뉴 활성 표시
side_active 'inbox' | 'mytasks' | 'trash' | '' — 개인 메뉴 활성 표시
is_admin 프로젝트 생성/수정/삭제 권한
프로젝트 수정/삭제(✎/×) 버튼은 그 동작을 배선하는 initProject 가 도는
프로젝트 화면에서만 그린다(current_pid 로 판별). #}
@@ -33,6 +33,13 @@
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
</a>
{# 휴지통 — 관리자만 보이고(화면·복구 API 도 관리자 전용), 지운 업무를 3개월 보관. #}
{% if is_admin %}
<a class="pj-side-navlink {% if side_active == 'trash' %}is-active{% endif %}" href="/project/trash">
<span class="material-symbols-outlined pj-side-navic">delete</span>
<span class="pj-side-navtext">휴지통</span>
</a>
{% endif %}
</nav>
<div class="pj-side-block">
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260924i" />
<link rel="stylesheet" href="/static/project.css?v=20260924j" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -98,5 +98,5 @@
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260924i" defer></script>
<script src="/static/project.js?v=20260924j" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260924i" />
<link rel="stylesheet" href="/static/project.css?v=20260924j" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -119,5 +119,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20260924i" defer></script>
<script src="/static/project.js?v=20260924j" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260924i" />
<link rel="stylesheet" href="/static/project.css?v=20260924j" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -505,5 +505,5 @@
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20260924i" defer></script>
<script src="/static/project.js?v=20260924j" defer></script>
{% endblock %}
@@ -0,0 +1,71 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260924j" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
{% block content %}
{# 휴지통 — 관리자 전용. 지운 업무(하위 업무·댓글·팔로워·첨부 포함)를 3개월
보관하고, [복구] 로 원래 id 그대로 되살린다(project_db 010). #}
<div class="pj-wrap pj-inbox-view pj-trash-view">
<div class="pj-layout">
{% with current_pid = 0, side_active = "trash" %}{% include "project/_side.html" %}{% endwith %}
<section class="pj-main">
<div class="pj-section-head">
<h2>휴지통</h2>
<span class="pj-trash-note">삭제한 업무는 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 관리자만 할 수 있습니다.</span>
</div>
<div class="pj-view pj-inbox-pane">
{% if not trash_enabled %}
<div class="pj-empty">
휴지통이 아직 준비되지 않았습니다(DB 마이그레이션 010 필요). 지금은 삭제하면 바로 영구 삭제됩니다.
</div>
{% elif not items %}
<div class="pj-empty">휴지통이 비어 있습니다.</div>
{% else %}
<table class="pj-table pj-trash-table" id="pj-trash-table">
<thead>
<tr>
<th>업무</th>
<th>프로젝트</th>
<th>포함</th>
<th>삭제한 사람</th>
<th>삭제일</th>
<th>남은 보관</th>
<th></th>
</tr>
</thead>
<tbody>
{% for it in items %}
<tr data-id="{{ it.id }}">
<td class="pj-trash-title">{{ it.title }}</td>
<td>{{ it.project_name or '-' }}</td>
<td class="pj-trash-meta">
{% if it.task_count > 1 %}하위 업무 {{ it.task_count - 1 }}{% endif %}
{% if it.comment_count %}{% if it.task_count > 1 %} · {% endif %}댓글 {{ it.comment_count }}{% endif %}
{% if it.attachment_count %} · 첨부 {{ it.attachment_count }}{% endif %}
{% if it.task_count <= 1 and not it.comment_count and not it.attachment_count %}-{% endif %}
</td>
<td>{{ it.deleted_by_id or '-' }}</td>
<td>{{ it.deleted_label }}</td>
<td>{% if it.days_left is not none %}{{ it.days_left }}일{% else %}-{% endif %}</td>
<td class="pj-trash-act">
<button type="button" class="pj-btn pj-btn-primary pj-trash-restore"
data-id="{{ it.id }}" data-title="{{ it.title }}" data-count="{{ it.task_count }}">복구</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</div>
</section>
</div>
</div>
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260924j" defer></script>
{% endblock %}